试图为JOIN查询引入一个简单的新条件

时间:2019-02-07 18:28:58

标签: sql sqlite

我正在使用SQLite,有人帮助我构造了很好的JOIN查询,但是现在我需要添加另一个条件,但是我很难在不破坏查询的情况下将其引入查询中。

在JOIN中使用的两个表中都有一个名为EventId的列,我想介绍一个简单的条件...

WHERE EventId = 123456

在下面,您可以看到查询本身的一个有效示例以及两个尝试引入新条件并失败的注释(因为我对SQL不满意)。

SELECT t.MicrosoftId, 
    SUM(CASE WHEN name = 'necktie' THEN 1 ELSE 0 END) as 'necktie',
    SUM(CASE WHEN name = 'shirt' THEN 1 ELSE 0 END) as 'shirt',
    SUM(CASE WHEN name = 'suit' THEN 1 ELSE 0 END) as 'suit',
    SUM(CASE WHEN name = 'man' THEN 1 ELSE 0 END) as 'man',
    SUM(CASE WHEN name = 'male' THEN 1 ELSE 0 END) as 'male' 
FROM TagsMSCV t 
        /* <---- WHERE t.EventId = 123456 (fails here...) */
LEFT JOIN 
(SELECT i.MicrosoftId
FROM Images i 
GROUP BY i.MicrosoftId) i 
ON i.MicrosoftId = t.MicrosoftId 
WHERE t.name IN ('necktie','shirt','suit','man','male') 
        /* <---- AND WHERE t.EventId = 123456 (fails here too...) */
GROUP BY t.MicrosoftId

2 个答案:

答案 0 :(得分:2)

尝试如下

select t1.* from   ( SELECT t.MicrosoftId, 
        SUM(CASE WHEN name = 'necktie' THEN 1 ELSE 0 END) as 'necktie',
        SUM(CASE WHEN name = 'shirt' THEN 1 ELSE 0 END) as 'shirt',
        SUM(CASE WHEN name = 'suit' THEN 1 ELSE 0 END) as 'suit',
        SUM(CASE WHEN name = 'man' THEN 1 ELSE 0 END) as 'man',
        SUM(CASE WHEN name = 'male' THEN 1 ELSE 0 END) as 'male' 
    FROM TagsMSCV t WHERE t.EventId = 123456 
  and name IN ('necktie','shirt','suit','man','male') group by t.MicrosoftId 
  ) t1

您在创建子查询时确实犯了错误,并且由于没有使用汇总函数,因此作为第二个子查询不需要分组依据

答案 1 :(得分:1)

它应该在WHERE部分中,但没有第二个WHERE关键字:

SELECT t.MicrosoftId, 
    SUM(CASE WHEN name = 'necktie' THEN 1 ELSE 0 END) as 'necktie',
    SUM(CASE WHEN name = 'shirt' THEN 1 ELSE 0 END) as 'shirt',
    SUM(CASE WHEN name = 'suit' THEN 1 ELSE 0 END) as 'suit',
    SUM(CASE WHEN name = 'man' THEN 1 ELSE 0 END) as 'man',
    SUM(CASE WHEN name = 'male' THEN 1 ELSE 0 END) as 'male' 
FROM TagsMSCV t 
LEFT JOIN 
(SELECT i.MicrosoftId
FROM Images i 
GROUP BY i.MicrosoftId) i 
ON i.MicrosoftId = t.MicrosoftId 
WHERE t.name IN ('necktie','shirt','suit','man','male') 
AND t.EventId = 123456
GROUP BY t.MicrosoftId