Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
735 views
in Technique[技术] by (71.8m points)

mysql - SQL Selecting From One Table With Multiple Where Clauses

Searching high and low for an answer to this one and having no luck. I'm sure it can't be as complicated as I think it is.

I have one table with titles and codes. The codes are unique and can have more than one titlecode. I want to be able to select those titles that have codes I list.

 Titles                        Codes
 -----------------------------------
 Book1                         001
 Book2                         010
 Book2                         020
 Book2                         021
 Book3                         030
 Book3                         040

So I want to be able to return Titles that have codes 020 and 021. Or whatever I list. In this case it would just return Book2 as that Title has those two codes.

I initially tried

 SELECT Titles FROM table WHERE Codes = 020 AND Codes = 021 

but that returned zero results and I could see why. No row contains more than one Codes entry

 SELECT Titles FROM table WHERE Codes = 020 OR Codes = 021 

returns Titles that are either. So I've been trying to use GROUP BY and also a subquery to try and get it but having no luck. Can anyone help please? Thanks in advance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a having clause:

SELECT Titles
FROM table
GROUP BY Titles
HAVING SUM(Codes = '020') > 0 AND SUM(Codes = '021') > 0;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...