如果某些表中存在使用SQL的行,则更新表行

时间:2018-04-03 14:19:04

标签: mysql sql

我有SQL查询:

SELECT COUNT(*) AS c 
FROM plan_acl 
WHERE plan_id = (SELECT id 
                 FROM plan 
                 WHERE unicateHash = '2xxxxxxxxxxxxMcxXqZoydkOltnadm1Uf' LIMIT 1)

哪个返回c作为计数。像这样:

c = 1

c = 0

如果c = 1我想要更新表。我该怎么做?

我试试:

SELECT IF(SELECT COUNT(*) AS c 
          FROM plan_acl 
          WHERE plan_id = (SELECT id 
                           FROM plan 
                           WHERE unicateHash = '2xxxxxxxxxxxxMcxXqZoydkOltnadm1Uf' LIMIT 1).c = 1, "YES", "NO");

但我收到了错误。

什么是错的?

1 个答案:

答案 0 :(得分:1)

如果要更新表格,可以使用以下语法:

UPDATE plan_acl a
    SET isActive = 0
    WHERE EXISTS (SELECT 1
                  FROM plan p
                  WHERE p.id = a.plan_id AND p.unicateHash = '2xxxxxxxxxxxxMcxXqZoydkOltnadm1Uf' 
                );

请注意,使用limit 1=的方法几乎完全相同,但EXISTS内置于SQL语言中,目的是测试行中是否存在行一张桌子。