行是否存在且多个在哪里

时间:2012-01-24 04:46:03

标签: sql where-clause

我刚问了这个问题Multiple Where conditions,但意识到还有更多问题(并且不想混淆另一个问题)。

我有一个看起来像这样的表:

meta_id - id - meta_key     - meta_value
1         1    school         Some School 1
2         2    school         Some School 2
3         2    hidden         1
4         3    school         Some School 3
5         4    school         Some School 4
6         5    school         Some School 5
7         5    hidden         1

感谢我之前的问题,我有这样的语法:

SELECT DISTINCT m1.id 
FROM metadata m1
join metadata m2 on m1.id = m2.id
WHERE (m1.meta_key = 'school' AND m1.meta_value = 'Some School 1') 
AND (m2.meta_key = 'hidden' AND m2.meta_value = '1')

,如果school = Some School 1hidden = 1

,则会找到该ID

但问题是行hidden只有在隐藏时才存在,如果没有隐藏它就不存在 - 所以它不像hidden = 0那么容易意味着它不被隐藏和{ {1}}表示隐藏。

所以我需要找出hidden = 1,同样school = Some School 1,行id不存在。

1 个答案:

答案 0 :(得分:1)

SELECT DISTINCT m1.id 
FROM metadata m1
WHERE 
    m1.meta_key = 'school' 
AND m1.meta_value = 'Some School 1' 
AND NOT EXISTS 
(
  SELECT * FROM metadata m2
  WHERE 
      m2.meta_key = 'hidden' 
  AND m2.meta_value = '1'
  AND m2.Id = m1.Id
)