gpt4 book ai didi

mysql - 查询 2 列,其中值从未在任一列中多次出现

转载 作者:行者123 更新时间:2023-11-30 22:04:00 26 4
gpt4 key购买 nike

寻找采用下表ProductList的查询

id| column_1  | column_2  | Sum  
================================
1 | Product-A | Product-B | 67
2 | Product-A | Product-C | 55
3 | Product-A | Product-D | 23
4 | Product-B | Product-C | 95
5 | Product-C | Product-D | 110

并返回第一条记录 Product-A_Product-B,然后跳过任一列中包含 Product-A 或 Product-B 的所有记录并返回 Product-C_Product-D。如果该行中的所有内容都是第一次出现,我只想返回该行。

最佳答案

假设产品不包含 ,,您可以使用逗号分隔的 session 变量来存储已选择的产品,并检查每一行是否其中一列已包含在该变量中:

select column_1, column_2
from (
select l.*,
case when find_in_set(l.column_1, @products) or find_in_set(l.column_2, @products)
then 1
else (@products := concat(@products, ',', l.column_1, ',', l.column_2)) = ''
end as skip
from ProductList l
cross join (select @products := '') init
order by l.id
) t
where skip = 0;

演示:http://rextester.com/NDVBW87988

但你应该知道风险:

    子查询中的
  1. ORDER BY 不是真正有效的,通常没有意义。引擎可能会跳过它或将其移动到外部查询。

  2. 如果在一条语句中读取和写入同一个 session 变量,则执行顺序没有定义。因此查询可能不适用于所有( future )版本。

关于mysql - 查询 2 列,其中值从未在任一列中多次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42355107/

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