Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.1k views
in Technique[技术] by (71.8m points)

sql - bulk delete from a many-to-many relation table based on a WHERE condition that checks ids in two lists

Assume that there is an employee table and a project table. A relationship table emp_proj contains following column: (id, emp_id, proj_id)

I would like to delete rows from emp_proj that contain following pairs of (emp_id, proj_id) : (1,101) , (1,102), (2,202), (3,303)

Note that the table may contain other rows with emp_ids 1, 2 and 3.

How would I use WHERE clause that would compare these pairs ?

I thought of using nesting of ORs but that would complicate the query.

Also I would like to do a bulk delete operation that in one-go, would delete all rows that contain the concerned pairs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

On Postgres, your suggested approach might be the only option:

DELETE
FROM emp_proj
WHERE
    emp_id = 1 AND proj_id = 101 OR
    emp_id = 1 AND proj_id = 102 OR
    emp_id = 2 AND proj_id = 202 OR
    emp_id = 3 AND proj_id = 303;

Note that on certain other databases, such as MySQL, you could have used a tuple syntax which is a bit more terse:

DELETE
FROM emp_proj
WHERE
    (emp_id, proj_id) IN ((1, 101), (1, 102), (2, 202), (3, 303));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...