MySQL只选择剩余的行

时间:2015-07-27 01:27:19

标签: mysql select

我有一张表:

id | name   | type  
 1 | a      | in  
 2 | a      | out  
 3 | a      | in  
 4 | a      | out  
 5 | a      | in  
 6 | b      | in  
 7 | b      | out  
 8 | b      | in  
 9 | c      | in  
10 | c      | out  

我想选择所有没有匹配in事件的out个事件。

5 | a  | in  
8 | b  | in  

有可能吗?

编辑:

来龙去世同名不必相互追随。

id | name   | type  
 1 | a      | in  
 2 | a      | out  
 3 | a      | in  
 4 | a      | out  
 5 | c      | in  
 6 | b      | in  
 7 | b      | out  
 8 | b      | in  
 9 | a      | in  
10 | c      | out  

2 个答案:

答案 0 :(得分:2)

一种方法是使用带有相关子查询的not exists谓词,该子查询检查是否存在任何' out' ID值高于' in' row(名称相同)。

select * from table1 a
where type = 'in'
and not exists (
  select 1 from table1 b 
  where a.name = b.name 
  and b.type = 'out' 
  and b.id > a.id
);

Sample SQL Fiddle

答案 1 :(得分:0)

这里你去....

SELECT t1.id,t1.name,t1.type
FROM `t` t1
JOIN `t` t2 on t1.id + 1=t2.id
where t2.type = t1.type

这里是完整的sql小提琴 http://sqlfiddle.com/#!9/90d87/6

  • 我已将表格与自身匹配,偏移量为1:t1.id+1 = t2.id
  • 然后我只提取相同的内容:where t2.type = t1.type

这会匹配任何连续相同的内容,如果 out s也发生并需要注意,请使用where t2.type = t1.type AND t1.type = 'in'