这是之前遇到过的一道sql面试题,供参考学习:
查找所有项目开始时间比之前项目结束时间小的项目ID
mysql> select * from t2; +----+---------------------+---------------------+ | id | start | end | +----+---------------------+---------------------+ | 1 | 2015-01-01 00:00:00 | 2015-01-29 00:00:00 | | 2 | 2015-01-01 00:00:00 | 2015-01-22 00:00:00 | | 3 | 2015-01-03 00:00:00 | 2015-01-20 00:00:00 | | 4 | 2015-02-03 00:00:00 | 2015-03-20 00:00:00 | | 5 | 2015-01-04 00:00:00 | 2015-01-15 00:00:00 | | 6 | 2015-01-18 00:00:00 | 2015-02-15 00:00:00 | +----+---------------------+---------------------+
数据如上所示,由人工观察可知id为2,3,5,6的数据列将需要被找出。
sql语句如下:
mysql> select distinct(a.id) from t2 a,t2 b where a.start<b.end and a.id>b.id; +----+ | id | +----+ | 2 | | 3 | | 5 | | 6 | +----+ 4 rows in set (0.00 sec)