MySQL将一个表连接到自身

时间:2010-10-23 19:14:27

标签: mysql join

请考虑下表'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 |  
+-------+-------+------+----+-------+-------+------+  

1 个答案:

答案 0 :(得分:6)

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