我正在寻找加入查询。其实我主要有三张桌子。
- Category [cat_id(PK), cat_name]
- Product [pro_id(PK), cat_id(FK),pro_name]
- Company [com_id(PK), cat_id(FK),pro_id(FK),...]
现在我在列表视图中有类别列表。因此,当用户点击删除时,应删除所选类别。
现在我可以检查单个表是否其他两个表使用了相同的cat_id
?
if(check cat_id is used in other tables or not)
{
alert("you can't delete because category is used by some other table(s).");
}
else
{
alert("record deleted.");
}
现在我可以使用NOT IN
之类的单表来检查相同的内容,
DELETE FROM CATEGORY WHERE cat_id NOT IN (SELECT DISTINCT cat_id FROM PRODUCT);
如果在PRODUCT表中不可用,则只会删除所选的cat_id。
即使我也尝试使用JOIN QUERY
,如下所示,
SELECT CATEGORY.cat_id FROM CATEGORY INNER JOIN PRODUCT ON CATEGORY.cat_id = PRODUCT.cat_id;
但我不知道如何使用第三张表。所以,我想知道如何检查多个表。
请帮助解决此问题。
答案 0 :(得分:4)
DELETE FROM CATEGORY WHERE cat_id NOT IN
(SELECT DISTINCT cat_id FROM PRODUCT) AND cat_id NOT IN
(SELECT DISTINCT cat_id FROM COMPANY)
答案 1 :(得分:1)
如果要在一个查询中执行删除和检查,可以使用
DELETE
FROM category
WHERE category.cat_id = ?
AND (SELECT COUNT(*) FROM product WHERE cat_id = ?) = 0
AND (SELECT COUNT(*) FROM company WHERE cat_id = ?) = 0
如果您只想检查是否存在与该键匹配的行,则可以运行
SELECT (SELECT COUNT(*) FROM product WHERE cat_id = ?)
AND (SELECT COUNT(*) FROM company WHERE cat_id = ?) AS matching_rows