MySQL - n to n table - how to select properly?

时间:2016-10-20 12:59:21

标签: mysql

I would like to know how can i select/update/delete in n:n table. My table:

id_rel | option
----------------
1      |    1
2      |    2
2      |    1
3      |    1
4      |    1
4      |    2
5      |    1
6      |    2

And now i want to check if some id_rel have option 1 and 2 - if it's true then delete row with option 2.

Desired effect:

id_rel | option
----------------
1      |    1
2      |    1
3      |    1
4      |    1
5      |    1
6      |    2

How can i do it?

1 个答案:

答案 0 :(得分:0)

Try this:

DELETE FROM mytable
WHERE `option` = 2 AND id_rel IN 
(
   SELECT id_rel
   FROM (SELECT id_rel
         FROM mytable
         GROUP BY id_rel
         HAVING SUM(`option`=1) > 0 AND SUM(`option`=2) > 0) AS t
);

The subquery:

SELECT id_rel
FROM mytable
GROUP BY id_rel
HAVING SUM(`option`=1) > 0 AND SUM(`option`=2) > 0

is used to identify id_rel values being related to both 1 and 2 options. This subquery has to be placed in another subquery because, otherwise, MySQL throws error:

Error Code: 1093. You can't specify target table 'mytable' for update in FROM clause