问题
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