Can't nail a MySQL query where I require multiple records from a table
I have the following tables:
CATEGORIES -- entry_id, cat_id
TITLES -- entry_id, title
DATA -- entry_id, date, body
For each record entered into the DB the same entry_id is entered into all three entry_id fields in the three tables. In the Categories table, it will post a record for each category I've such as:
entry_id: 100 cat_id:24
entry_id: 100 cat_id:31
entry_id: 100 cat_id:17
(say cat_id 24 is web_design, 31 is coding and 17 is ajax)
THE PROBLEM: I'm having a bugger of a time selecting only records that have a recor开发者_StackOverflowd for BOTH cat_id 24 and 17 in the Categories table along with other fields. Here's what I've got. I know it's crude but it gets me almost all the way there:
SELECT
data.entry_id,
data.date,
data.body,
titles.entry_id,
titles.title AS biz_name,
categories.entry_id,
categories.cat_id
FROM data, titles, categories
WHERE data.entry_id = titles.entry_id
AND data.entry_id = categories.entry_id
AND categories.cat_id = '24'
This will display everything with a cat_id of 24 but when I add
AND categories.cat_id = '17'
to the very end of the query, nothing is returned.
Any thoughts?
SELECT
data.entry_id,
data.date,
data.body,
titles.entry_id,
titles.title AS biz_name,
categories.entry_id,
categories.cat_id
FROM data, titles, categories
WHERE data.entry_id = titles.entry_id
AND data.entry_id = categories.entry_id
AND categories.cat_id IN (17,24)
SELECT
data.entry_id,
data.date,
data.body,
titles.entry_id,
titles.title AS biz_name,
FROM data
JOIN titles ON data.entry_id = titles.entry_id
INNER JOIN categories cat1 ON data.entry_id = cat1.entry_id AND cat1.cat_id=17
INNER JOIN categories cat2 ON data.entry_id = cat2.entry_id AND cat2.cat_id=24
WHERE ((cat1.cat_id) = (17)) AND ((cat2.cat_id) = (24))
This new query correctly filters for only the ones with both
If you want to add one condition to another you use OR
.. AND (categories.id='24' OR categories.id='17';
This will include both 24 and 17 in your result
精彩评论