gpt4 book ai didi

MySQL 左连接一个表到它自己

转载 作者:行者123 更新时间:2023-11-29 04:13:36 26 4
gpt4 key购买 nike

请考虑下表'mmm':

select * from mmm;

输出:

+-------+-------+------+  
| texto | value | n |
+-------+-------+------+
| aaa | 10 | 1 |
| aab | 10 | 1 |
| aaa | 11 | 1 |
| aab | 11 | 1 |
| aaa | 10 | 2 |
+-------+-------+------+

命令:

select a.*, '--', b.* 
from mmm a
left join mmm b on (a.n=b.n)
where a.value < b.value
and a.texto ='aaa'
and b.texto='aab';

返回:

+-------+-------+------+----+-------+-------+------+  
| texto | value | n | -- | texto | value | n |
+-------+-------+------+----+-------+-------+------+
| aaa | 10 | 1 | -- | aab | 11 | 1 |
+-------+-------+------+----+-------+-------+------+

没关系。但我想要的是这样的:

+-------+-------+------+----+-------+-------+------+  
| texto | value | n | -- | texto | value | n |
+-------+-------+------+----+-------+-------+------+
| aaa | 10 | 1 | -- | aab | 11 | 1 |
+-------+-------+------+----+-------+-------+------+
| aaa | 10 | 2 | -- | NULL | NULL | NULL |
+-------+-------+------+----+-------+-------+------+

最佳答案

select a.*, '--', b.* 
from mmm a
left join mmm b on (a.n=b.n)
where (a.value < b.value or b.value is null)
and a.texto ='aaa'
and (b.texto='aab' or b.textto is null);

或:

select a.*, '--', b.* 
from mmm a
left join mmm b on (a.n=b.n and a.value < b.value and b.texto = 'aab')
where a.texto ='aaa' ;

关于MySQL 左连接一个表到它自己,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4005643/

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