同一查询在重复执行时返回不同的值

yrdbyhpb  于 2021-06-19  发布在  Mysql
关注(0)|答案(1)|浏览(456)

正在使用的数据库:5.6(我不能使用mysql 8中的lag函数)
我在mysql中有下面的表结构

book_id     | Version      | Rating | Price 
varchar(25) | Decimal(10,2)| int    | Decimal(10,2)

我有一个网页,上面有两张图表。
在第一个图表中,我将显示用于评级的书籍数量(评级仅从1到4),但仅显示最新版本的书籍。 Query1 在第二个图表中,我将显示一个价格范围内的图书数量,但只显示最新版本的图书。 Query2 每次加载或刷新网页时,这两个查询都会相继运行。虽然数据保持不变,但对于同一个查询,有时会得到不同的结果。
我有以下两个几乎相同的查询
查询1

SELECT  
       SUM(CASE WHEN rating=1 THEN 1 ELSE 0) AS rating1,
       SUM(CASE WHEN rating=2 THEN 1 ELSE 0) AS rating2,
       SUM(CASE WHEN rating=3 THEN 1 ELSE 0) AS rating3,
       SUM(CASE WHEN rating=4 THEN 1 ELSE 0) AS rating4
FROM (
       SELECT rating, row_number
       FROM (
              SELECT rating, 
                     @num:=IF(@group:=book_id, @num+1, 1) row_number,
                     @group:=book_id bi
              FROM book_database
              ORDER BY book_id, version DESC
             ) book
      HAVING book.row_number = 1
    ) book

查询2

SELECT  
       SUM(CASE WHEN price <= 1000 THEN 1 ELSE 0) AS cheap,
       SUM(CASE WHEN price >1000 THEN 1 ELSE 0) AS costly
FROM (
       SELECT price, row_number
       FROM (
              SELECT price, 
                     @num:=IF(@group:=book_id, @num+1, 1) row_number,
                     @group:=book_id bi
              FROM book_database
              ORDER BY book_id, version DESC
             ) book
      HAVING book.row_number = 1
    ) book

在我的网页中有多个屏幕,有多个查询,但它们中的大多数工作在同一个逻辑上。基本上,我将查询任何书籍的最新版本,因此我使用嵌套查询。
有时,当同一个查询在同一个数据集上运行多次时,我得到的结果与预期的不同。
我的问题对吗?变量的使用导致了这个问题吗?由于多个查询是并行运行的(尽管在不同的数据库连接中),变量的使用是可疑的?

qoefvg9y

qoefvg9y1#

您使用的变量不正确。mysql不保证表达式在 SELECT 子句,所以您应该同时设置所有变量。
例如,第一个查询应该更像这样:

SELECT SUM( rating = 1 ) AS rating1,
       SUM( rating = 2 ) AS rating2,
       SUM( rating = 3 ) AS rating3,
       SUM( rating = 4 ) AS rating4
FROM (SELECT rating, book_id,
             (@rn := if(@b = book_id, @rn + 1,
                        if(@b := book_id, 1, 1)
                       )
             ) as rn
      FROM (SELECT rating, book_id, version
            FROM book_database
            ORDER BY book_id, version DESC
           ) book CROSS JOIN
           (SELECT @rn := 0, @b := -1) params
    ) book
WHERE rn = 1;

重要的部分是涉及变量的部分。我还简化了其他一些逻辑。
但是,这不需要变量:

SELECT SUM( rating = 1 ) AS rating1,
       SUM( rating = 2 ) AS rating2,
       SUM( rating = 3 ) AS rating3,
       SUM( rating = 4 ) AS rating4
FROM book_database b
WHERE b.version = (SELECT MAX(b2.version)
                   FROM book_database b2
                   WHERE b2.book_id = b.book_id
                  );

带索引的 book_database(book_id, version) ,这应该比使用变量的版本快。

相关问题