简体   繁体   中英

MySQL, how to get rows that have certain columns

I have a table like this:

|  ID1   |  ID2  |
------------------
|   1    |   1   |
|   2    |   1   |
|   3    |   1   |
|   4    |   1   |
|   5    |   1   |
|   6    |   1   |
|   7    |   1   |
|   8    |   1   |
|   9    |   1   |
|   10   |   1   |
|   11   |   1   |
|   12   |   1   |
|   13   |   1   |
|   1    |   2   |
|   2    |   2   |
|   5    |   2   |
|   1    |   4   |
|   9    |   4   |

Some of the ID1s have both the 1 and 4 values like this:

想要的值

And I would like to return the ID1s like this:

|  ID1   |
----------
|   1    |
|   9    |

I have tried some basic queries but Im not even close.. I just cannot get this to work even remotely and I need some serious help with this one.

Try this:

select id1
from yourtable
where id2 in (1,4)
group by id1
having count(distinct id2) = 2

Demo Here

If ID1 is supposed to have only one unique value then the following query would work for you:

SELECT 
 ID1
FROM your_table
GROUP BY ID1
HAVING COUNT(DISTINCT ID2) > 1;

EDIT: May be you are looking for those entries having ID2 as 1 and 4 both .

SELECT 
 ID1
FROM your_table
WHERE ID2 IN (1,4)
GROUP BY ID1
HAVING COUNT(DISTINCT ID2) = 2;

Note: It would have been better if you clarify what combination of ID1 & ID2 is supported in your table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM