0

我会简短:

在职的

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;

不工作

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;

所以,我需要“不工作”的版本才能工作。我怎样才能做到这一点?

我有同样的错误:'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''

为什么?类型没问题,你看... 什么问题?也许值可以用一些错误代替?

我正在使用 JetBrains DataGrip,MySQL 8.0.15。

4

1 回答 1

1

使用准备好的语句已经解决了这个问题。编码:

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;
于 2019-05-04T19:03:08.980 回答