gpt4 book ai didi

mysql - MySQL UNION 中的语句评估顺序和变量赋值

转载 作者:行者123 更新时间:2023-11-29 05:38:40 25 4
gpt4 key购买 nike

问题:在下面的 UNIONized 查询中,如何在评估相关派生查询之前强制分配 @col?要求:需要在一次查询中完成。

CREATE TABLE tbl (col CHAR(1) NOT NULL UNIQUE);

INSERT INTO tbl (col) VALUES ('a'), ('b'), ('c'), ('d'), ('e'), ...;

-- Now, for some value of "col", fetch that record and the
-- immediately preceding and following records as ordered by "col"
--
-- If you care to test this, be sure to SET @col := NULL before
-- subsequent executions to simulate a "fresh" MySQL session...
--
SELECT @col := col AS col -- Fetch particular record given a value of
FROM tbl -- "col".
WHERE col = 'd'
UNION ALL
SELECT col -- Fetch the immediately preceding record,
FROM ( SELECT col -- ordered by "col"
FROM tbl
WHERE col < @col
ORDER BY col DESC
LIMIT 1) preceding
UNION ALL
SELECT col -- Fetch the immediately following record,
FROM ( SELECT col -- ordered by "col"
FROM tbl
WHERE col > @col
ORDER BY col ASC
LIMIT 1) following
ORDER BY col ASC;

背景: 从上面的 UNIONized 查询中,我希望获得三个记录:一个匹配精确且唯一的“col”值的记录,以及按“col”排序的紧接前后的记录。

但是,查询的第一次 运行只产生一个记录,该记录与用户提供的“col”值相匹配。随后的运行给了我预期的三个。我的推断是 @col 直到派生查询 precedingfollowing 被评估后才被分配——这不是从左到右-我期望的从上到下的评估顺序。

(我试图完善 this question 的答案,但遇到了这个困难。)

最佳答案

不要将 @col 的赋值与您的其他查询联合。

用一个查询为@col 赋值,用一个单独的查询将该记录包含在结果中。

SELECT @col := col AS col    -- Fetch particular record given a value of
FROM tbl -- "col", assigning the identifier to @col.
WHERE col = 'd'



SELECT col -- Now include the above record in the
FROM tbl -- Final result-set
WHERE col = @col

UNION ALL

SELECT col -- Fetch the immediately preceding record,
FROM ( SELECT col -- ordered by "col"
FROM tbl
WHERE col < @col
ORDER BY col DESC
LIMIT 1) preceding

UNION ALL

SELECT col -- Fetch the immediately following record,
FROM ( SELECT col -- ordered by "col"
FROM tbl
WHERE col > @col
ORDER BY col ASC
LIMIT 1) following
ORDER BY col ASC;

关于mysql - MySQL UNION 中的语句评估顺序和变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8578419/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com