I'll be brief:
WORKING
SELECT p.id,
p.name,
cat.name `category`,
prod.name `producer`,
p.images,
p.price,
p.flag_avaliable,
p.amount,
p.description,
p.options
FROM product p
INNER JOIN product_category cat ON cat.id = p.category_id
INNER JOIN product_producer prod ON prod.id = p.producer_id
ORDER BY @asc_or_desc
limit 5 offset 6;
NOT WORKING
set @asc_or_desc = 'id desc ';
set @limit_number = 5;
set @offset_number = 6;
SELECT p.id,
p.name,
cat.name `category`,
prod.name `producer`,
p.images,
p.price,
p.flag_avaliable,
p.amount,
p.description,
p.options
FROM product p
INNER JOIN product_category cat ON cat.id = p.category_id
INNER JOIN product_producer prod ON prod.id = p.producer_id
ORDER BY @asc_or_desc
limit @limit_number offset @offset_number;
So, I need the 'not working' version to work. How can I do that?
I have the same error: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@limit_number offset @offset_number; END''
.
Why? Types are ok, you see... What the problem? Maybe values are substitute with some bug?
I'm using JetBrains DataGrip, MySQL 8.0.15.
Using prepared statements have solved the problem. The code:
set @statement =
concat('SELECT p.id,
p.name,
cat.name `category`,
prod.name `producer`,
p.images,
p.price,
p.flag_avaliable,
p.amount,
p.description,
p.options
FROM product p
INNER JOIN product_category cat ON cat.id = ?
INNER JOIN product_producer prod ON prod.id = p.producer_id
ORDER BY id ',@asc_or_desc,'
limit ? offset ?');
prepare prepared from @statement;
EXECUTE prepared USING @category_id, @limit_number, @offset_number;
DEALLOCATE PREPARE prepared;