MySQL - delete where not in find_in_set

倾然丶 夕夏残阳落幕 提交于 2021-01-28 03:21:45

问题


I'm trying to find the right syntax to delete records that are not in a comma separated row.

table A

| id | product_id | attribute_id |
|----|------------|--------------|
| 1  | 123        | 45           |
| 2  | 123        | 46           |
| 3  | 124        | 34           |
| 4  | 124        | 33           |

table B

| code | Axis  |
|------|-------|
| 123  | 45,46 |
| 124  | 34    |

My goal is to remove all rows from table A where the attribute id is not in the table B axis value (in this example the row with id = 4).

I try to do a SELECT before:

SELECT A.attribute_id, A.product_id
FROM tableA as A
LEFT JOIN (SELECT * FROM tableB) AS B
ON FIND_IN_SET(A.attribute_id, B.`axis`)

But without any luck.

How can I do this?


回答1:


You can try the following to SELECT the data:

SELECT A.attribute_id, A.product_id 
FROM tableA AS A LEFT JOIN tableB AS B ON A.product_id = B.code
WHERE IFNULL(FIND_IN_SET(A.attribute_id, B.Axis), 0) = 0

You can use the following to DELETE the rows on table A (based on SELECT):

DELETE FROM tableA WHERE id IN (
    SELECT A.id 
    FROM tableA AS A LEFT JOIN tableB AS B ON A.product_id = B.code
    WHERE IFNULL(FIND_IN_SET(A.attribute_id, B.Axis), 0) = 0
)

demo: http://sqlfiddle.com/#!9/3a3e13/6/0




回答2:


How about this one:

DELETE FROM tableA WHERE id IN
(
 SELECT A.id
 FROM tableA AS A
 LEFT JOIN tableB AS B
 ON A.product_id = B.code AND FIND_IN_SET(CONCAT(A.attribute_id), B.Axis) = 0;
)

If your attribute_id field is char or varchar, just ignore the CONCAT function.



来源:https://stackoverflow.com/questions/48560910/mysql-delete-where-not-in-find-in-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!