Yaser Darzi Yaser Darzi - 12 days ago 5
MySQL Question

i need help to find solution for this query in MySQL?

i have one table MySQL for like this

id p_id c_id

1 11 1

2 11 2

3 11 3

4 12 1

5 12 3

6 13 1

7 13 2


i need query when is the c_id 1 and 2

it return value back for me p_id 11 and 13

SELECT DISTINCT p_id FROM `Table Name` where c_id in (1,2)


this return me
11 , 12 , 13

but i need only 11 , 13

Answer

You can write your query as:

SELECT DISTINCT a.p_id 
FROM table_name AS a
JOIN table_name AS b ON a.p_id=b.p_id
WHERE a.c_id ='1' AND b.c_id ='2';

It's a self-join on the table itself