Does row exist and multiple where

微笑、不失礼 提交于 2019-12-12 04:35:48

问题


I just asked this question Multiple Where conditions, but realised there was more to it (and didn't want to confuse the other question).

I have a table that looks like this:

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

Thanks to my previous question I have this syntax:

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')

which finds the id if the school = Some School 1 and hidden = 1

But the problem is that the row hidden is only there if it is hidden, it doesn't exist if its not hidden - so its not as easy as hidden = 0 means its not hidden and hidden = 1 means its hidden.

So I need to find out school = Some School 1 and that for the same the id, the row hidden doesn't exist.


回答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
)


来源:https://stackoverflow.com/questions/8982099/does-row-exist-and-multiple-where

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!