在列上查找具有特定条件的行

时间:2018-07-09 08:12:18

标签: sql

我正在尝试执行一个sql查询,在该查询中我将所有行相互比较并检查它们的列。使用条件,我将显示需要的行。

我做了这个,却收到一条错误消息“ UNKNOWN COLUMN”,有什么想法要解决吗?

select * from table1 as tb1 where DATE_FORMAT(start_datetime, '%H:%i:%s') in (
    select DATE_FORMAT(start_datetime, '%H:%i:%s') from table1 as tb2
    group by DATE_FORMAT(start_datetime, '%H:%i:%s') having count(*) > 2 AND (end_datetime = start_datetime) OR (tb1.code = tb2.code)                                     
) AND user_id = 1

解释我想做什么,我正在搜索具有相同时间的行,然后如果start_datetime等于end_datetime或行具有相同的代码

在此 example我的sql查询应该返回最后4行,其中2行是因为它们具有相同的start_datetime和end_datetime,而2行是因为它们在start_datetime上具有相同的时间,相同的代码,并且end_datetime为NULL

2 个答案:

答案 0 :(得分:0)

尽管有任何错误,但由于您未提供架构而看不到,“ fs1.code”和“ fs2.code”似乎没有引用语句中定义的表别名。确实定义的别名是“ tb1”和“ tb2”,它们不匹配。

答案 1 :(得分:0)

您可以在2个数据集之间使用“全部合并”运算符

    select code,start_datetime,end_datetime from table2
    where  start_datetime=end_datetime

    union all

select t2.code,t2.start_datetime,t2.end_datetime from 
    (
    select code,start_datetime,end_datetime from table2
    where  start_datetime!=end_datetime
    and end_datetime is null    
    ) as t2
inner join ( select code table2 group by DATE_FORMAT(start_datetime, '%H:%i:%s'),code having count(*)>=2 )as t1 on t2.code=t1.code
相关问题