如何重写此 MySQL 查询以返回计数?
How can I rewrite this MySQL query for returning a count?
我有这个查询:
SELECT accounts.id
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
GROUP BY accounts.id
HAVING COUNT(account_properties.id) = 0
它returns 其帐户没有任何帐户属性的所有帐户 ID 的列表。如何获取没有属性的所有帐户的数量?
SELECT COUNT(accounts.id)
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
GROUP BY accounts.id
HAVING COUNT(account_properties.id) = 0
这不起作用,只有 returns 1 的列表。
select count(*) from (SELECT accounts.id
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
WHERE exists account_properties.id
GROUP BY accounts.id)
您可能会发现这些查询更快...假设 id 是帐户的唯一标识符。
对于 ids:
SELECT accounts.id
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
WHERE account_properties.id IS NULL
对于ids的计数:
SELECT COUNT(*)
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
WHERE account_properties.id IS NULL
SELECT `ap`.account_id IS NULL AS noProperties
, COUNT(DISTINCT `a`.id) AS accountCount
FROM `accounts` AS `a`
LEFT JOIN `account_properties` AS `ap` N `ap`.account_id = `a`.id
GROUP BY noProperties
HAVING noProperties
;
GROUP BY 获取有和没有属性的帐户数量,HAVING 过滤结果,以便最终结果中只有没有 属性 个帐户的计数。
我有这个查询:
SELECT accounts.id
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
GROUP BY accounts.id
HAVING COUNT(account_properties.id) = 0
它returns 其帐户没有任何帐户属性的所有帐户 ID 的列表。如何获取没有属性的所有帐户的数量?
SELECT COUNT(accounts.id)
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
GROUP BY accounts.id
HAVING COUNT(account_properties.id) = 0
这不起作用,只有 returns 1 的列表。
select count(*) from (SELECT accounts.id
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
WHERE exists account_properties.id
GROUP BY accounts.id)
您可能会发现这些查询更快...假设 id 是帐户的唯一标识符。
对于 ids:
SELECT accounts.id
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
WHERE account_properties.id IS NULL
对于ids的计数:
SELECT COUNT(*)
FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
WHERE account_properties.id IS NULL
SELECT `ap`.account_id IS NULL AS noProperties
, COUNT(DISTINCT `a`.id) AS accountCount
FROM `accounts` AS `a`
LEFT JOIN `account_properties` AS `ap` N `ap`.account_id = `a`.id
GROUP BY noProperties
HAVING noProperties
;
GROUP BY 获取有和没有属性的帐户数量,HAVING 过滤结果,以便最终结果中只有没有 属性 个帐户的计数。