Salavat
Salavat

Reputation: 111

Select data from one table by two fields

Structure of my table is

item_id (int)
category_id (int)

Here is some sample data:

╔═════════╦═════════════╗
║ item_id ║ category_id ║
╠═════════╬═════════════╣
║    2    ║      4      ║
║    2    ║      5      ║
║    3    ║      5      ║
║    6    ║      9      ║
║    1    ║      2      ║
║    4    ║      5      ║
║    6    ║      3      ║
║    4    ║      4      ║
╚═════════╩═════════════╝

I cant select one row by multiple select by second field.

FOR EXAMPLE, I need to select all rows that include category_id = 4 and 5

Upvotes: 1

Views: 80

Answers (1)

Alex
Alex

Reputation: 17289

I guess you need something like:

http://sqlfiddle.com/#!9/019c4/2

SELECT item_id 
FROM items
WHERE category_id IN (4, 5)
GROUP BY item_id 
HAVING COUNT(DISTINCT category_id)=2

Upvotes: 1

Related Questions