4

我正在寻找连接查询。其实我有主要的三张桌子。

- 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现在我可以使用like从单个表中检查相同的东西,

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;

但我不知道如何使用第三张表。所以,我想知道如何检查多个表。

请帮助解决这个问题。

4

2 回答 2

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)
于 2013-09-20T10:19:06.310 回答
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
于 2013-09-20T13:13:35.417 回答