我有一张桌子,必须确认他们对活动的帮助。此活动的能力有限。我想计算确认人数并在同一原子查询中更新确认状态。
假设PEOPLE表有id和确认字段。
我尝试过这样的事情:
UPDATE PEOPLE
SET confirmed = 'Y'
WHERE
id = 'ID_VALUE'
AND
(
SELECT amount
FROM
(
SELECT
COUNT(*) AS amount
FROM
PEOPLE AS p
WHERE
p.confirmed = 'Y'
) AS aux1
) < CAPACITY_LIMIT
表格示例:
-------------------
| id | confirmed |
-------------------
| 1 | N |
-------------------
| 2 | N |
-------------------
| ... | ... |
-------------------
| 10 | N |
-------------------
如果CAPACITY_LIMIT = 5并且我尝试从id = 1到id = 10顺序确认,我想执行更新(confirm ='Y')直到id = 5.
我确信我错过了一些东西,但我无法弄清楚它是什么。
提前致谢。问候。
答案 0 :(得分:1)
试试这个:
UPDATE
PEOPLE AS p1
INNER JOIN
(SELECT COUNT(*) AS numConfirmed FROM PEOPLE AS p2 WHERE p2.confirmed = 'Y') aux
SET
p1.confirmed = 'Y'
WHERE
p1.id = 'ID_VALUE'
AND aux.numConfirmed < CAPACITY_LIMIT;
答案 1 :(得分:0)
试试这个
SET @ct := (SELECT
COUNT(*) AS amount
FROM
PEOPLE AS p
WHERE
p.confirmed = 'Y');
UPDATE PEOPLE
SET confirmed = 'Y'
WHERE
id = '1'
AND CAPACITY_LIMIT < @ct
;
答案 2 :(得分:0)
falvarez, 您可能想要验证您的输入('ID_VALUE',CAPACITY_LIMIT)是否正确,包括数据类型和实际值,因为相同的查询对我没有任何问题。以下是我对我的测试表运行的查询(因为您可以看到查询框架与您的完全相同):
更新t_order set customer ='NewCustomerName',其中id = 124和 (从(选择计数(*)作为来自客户非空的t_order的金额中选择的金额)总计)&lt; 10