简体   繁体   中英

Find IDs of differing values grouped by foreign key in MySQL

I have a table

process with the fileds id , fk_object and status .

example

id| fk_object | status
----------------------
1 | 3         | true
2 | 3         | true
3 | 9         | false
4 | 9         | true
5 | 9         | true
6 | 8         | false
7 | 8         | false

I want to find the id s of all rows where different status exists grouped by fk_object .

in this example it should return the id s 3, 4, 5 , because for the fk_object 9 there existing status with true and false and the other only have one of it.

This gets the fk_object values with that property:

select fk_object
from process
group by fk_object
having min(status) <> max(status);

You can get the corresponding rows by using a join :

select p.*
from process p join
     (select fk_object
      from process
      group by fk_object
      having min(status) <> max(status)
     ) pmax
     on p.fk_object = pmax.fk_object;
Select id from process 
    where fk = ( select fk from process where status in ('true','false'));

The stock response is as follows...

SELECT ... FROM ... WHERE ... IN ('true','false')... GROUP BY ... HAVING COUNT(DISTINCT status) = 2;

where '2' is equal to the number of arguments in IN()

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