在where子句中使用Multiple AND condition

时间:2013-02-08 09:06:59

标签: sql database

我有一张名为Manuscript

的表格
BOOKID  AUTHORID BOOKNAME       GENRE   NOOFCOPIES  AMOUNT
B105    A102     Diagnosis      Journal 500         10000
B102    A102     The Essence... Fiction 110         11000
B106    A102     Clinical Sci.  Educat. 125         18750
B104    A103     Mind Games     Fiction 200         20000
B100    A102     Sublime        Fiction 100         10000
B101    A105     C Programming  Educati 125         18750
B103    A101     Scribe         Journal 500         10000
B107    A101     Clinical Chem. Educat. 125         54646
B108    A103     Clinical Chem. Educat. 125         54646   

如何获得已在所有类型中出版图书的AuthorId?预期输出A102

3 个答案:

答案 0 :(得分:3)

即使添加了更多类型的通用查询,

select "AUTHORID"
  from table1
 group by "AUTHORID"
having count(distinct "GENRE") = (select count(distinct "GENRE") from table1)

SQLFIDDLE link to above query

答案 1 :(得分:2)

蛮力方法可能类似于

SELECT DISTINCT AUTHORID
FROM Manuscript
WHERE AUTHORID IN 
  (SELECT AUTHORID FROM Manuscript WHERE GENRE LIKE 'Journal')
AND AUTHORID IN
  (SELECT AUTHORID FROM Manuscript WHERE GENRE LIKE 'Fiction')
AND AUTHORID IN
  (SELECT AUTHORID FROM Manuscript WHERE GENRE LIKE 'Education')

答案 2 :(得分:1)

一种可能的解决方案是获取不同类型的计数,然后根据:

进行过滤
select 
  authorid, count(distinct genre)
from 
  Manuscript
group by 
  authorid
having 
  count(distinct genre) = (select count(distinct genre) from Manuscript)