MySQL left join one table to itself

2019-08-03 05:12发布

Please consider the following table 'mmm':

select * from mmm;

Output:

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

The command:

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';

returns:

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

That's fine. But what I want is something like:

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

标签: mysql join
1条回答
手持菜刀,她持情操
2楼-- · 2019-08-03 05:22
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);

or:

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' ;
查看更多
登录 后发表回答