需要有关查询的帮助

时间:2010-09-04 16:59:12

标签: sql mysql

您有以这种方式组织的2个桌子:

table_users
|user_id|username|

table_products
|product_id|user_id|

现在,我在'table_products'中有一些孤儿条目。 通过此查询,我可以查看我有多少产品:

SELECT count(product_id) FROM table_products

此查询显示与用户关联的产品数量:

SELECT p.product_id, u.username
FROM table_products AS p
JOIN table_users AS u ON u.user_id = p.user_id

我需要一个允许我选择并删除所有孤儿产品的查询。 有人可以帮帮我吗?

2 个答案:

答案 0 :(得分:2)

使用NOT IN:

DELETE FROM TABLE_PRODUCTS 
 WHERE user_id NOT IN (SELECT u.user_id
                         FROM TABLE_USERS u)

使用NOT EXISTS:

DELETE FROM TABLE_PRODUCTS 
 WHERE NOT EXISTS (SELECT NULL 
                     FROM TABLE_USERS u
                    WHERE u.user_id = TABLE_PRODUCTS.user_id)

使用LEFT JOIN / IS NULL:

   DELETE TABLE_PRODUCTS 
     FROM TABLE_PRODUCTS p
LEFT JOIN TABLE_USERS u ON u.user_id = p.user_id
    WHERE u.user_id IS NULL

效率(仅限MySQL)

如果TABLE_PRODUCTS.user_id is nullable, the NOT IN and NOT EXISTS are more efficient选择。否则,LEFT JOIN is the most efficient choice in MySQL when the columns compared can not be null

附录

检查并仔细检查您是否在执行操作之前选择了要删除的正确行,方法是将“DELETE FROM”替换为“SELECT * FROM”。此外,如果使用InnoDB表 - 在事务中封装DELETE,那么您可以在必要时使用ROLLBACK

答案 1 :(得分:1)

警告:对于使用此查询删除的数据,我不承担任何责任。在运行生产数据之前,始终在测试数据库上进行测试。

DELETE p 
FROM table_products AS p 
LEFT JOIN table_users AS u 
USING (user_id) 
WHERE u.user_id IS NULL