0

我的 SQL 数据库中有两个表,一个是 Companies,另一个是 Company_advertisements。我想更新公司表“adv”的字段

SET Company.adv = 1 if Company_adv.image is not empty
SET Company.adv = 0 if Company_adv.image is empty

Company_adv 表的外键是 company_id

我尝试使用以下语法,但没有成功。相反,在运行此查询后,Companmy.adv 的所有值都变为 1

我试过这个查询:

UPDATE companies cmp, company_adv cma 
SET    cmp.adv=1 
WHERE  cma.company_id=cmp.id AND 
       cma.image1 IS NOT NULL

请帮我 !!

4

2 回答 2

0

如果是这种情况,您需要使用LEFT JOIN

UPDATE  companies cmp
        LEFT JOIN company_adv cma
            ON cmp.id = cma.company_id
SET     cmp.adv = IF(cma.image1 IS NULL, 0, 1)
于 2013-01-27T07:06:37.430 回答
0

你可以试试:

UPDATE companies
   SET adv=IF((SELECT image
                 FROM company_adv
                WHERE companies.id=company_adv.company_id) IS NULL,
              0,
              1);
于 2013-01-27T07:30:46.060 回答