根据子表从多个表中删除多个记录

时间:2018-03-15 12:02:17

标签: php mysql

我需要删除具有唯一ID的多个表数据。

如果子表不存在,我需要删除该表数据。

我尝试了isnull,如果是null选项,但它不起作用: -

SELECT * FROM carbrand 
INNER JOIN carmodel 
INNER JOIN carversion 
WHERE 
(
     (carmodel.brandid = carbrand.recid) OR 
     (carmodel.brandid = '')
) 
AND 
(
     (carversion.brandid = carbrand.recid) OR 
     (carversion.brandid = '')
 ) 
 AND carbrand.recid = 17

2 个答案:

答案 0 :(得分:0)

您需要使用ON在每个表上指定JOIN的条件。如果你想要JOINS可能不会返回匹配,请使用LEFT JOIN,INNER JOIN只返回有匹配的记录...

SELECT * FROM carbrand 
LEFT JOIN carmodel ON carmodel.brandid = carbrand.recid
LEFT JOIN carversion ON carversion.brandid = carbrand.recid
WHERE carbrand.recid = 17

使用LEFT JOIN,如果找不到记录,该表中的所有值都将为空。

答案 1 :(得分:0)

尝试以下代码

SELECT * FROM carbrand 
INNER JOIN carmodel 
INNER JOIN carversion 
WHERE 
(
    (carmodel.brandid = carbrand.recid) OR 
    (carmodel.brandid IS NULL)
) 
AND 
(
    (carversion.brandid = carbrand.recid) OR 
    (carversion.brandid IS NULL)
) 
AND carbrand.recid = 17