Java 如何重写此MySQL查询以返回计数?

Java 如何重写此MySQL查询以返回计数?,java,mysql,sql,jdbc,Java,Mysql,Sql,Jdbc,我有一个疑问: 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 它返回其帐户没有任何帐户属性的所有帐户ID的列表。如何获取所有没有属性的帐户的计数 SELECT COUNT(accounts.id) F

我有一个疑问:

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
它返回其帐户没有任何帐户属性的所有帐户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
这不起作用,只返回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是帐户的唯一标识符

对于ID:

   SELECT accounts.id
     FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
    WHERE account_properties.id IS NULL
有关ID的计数:

   SELECT COUNT(*)
     FROM accounts
LEFT JOIN account_properties ON account_properties.account_id = accounts.id
    WHERE account_properties.id IS NULL

GROUP BY获取包含属性和不包含属性的帐户数,HAVING筛选结果,以便最终结果中仅包含无属性帐户的计数。

我认为HAVING使用的计数将始终为1(除非帐户具有多个属性)。这不是他筛选属性为0的记录的方式吗?或者你是说,即使它不=0,它仍然会返回为1?是的,
COUNT
实际上只是计算行数,使用
左连接
每个帐户将至少获得一行。由于这个原因,他的查询无法返回他期望的结果。那怎么办?我用的是where exists?我不确定,我从来没有实际使用过
exists
。谢谢。使用GROUPBY/HAVING检索ID首先感觉是错误的。这样好多了。我不知道检查是否有列被连接的IS NULL技巧。是的,这就是我的意思say@Aich我的荣幸。。这是相当普遍的。如果必须的话,不要害怕用计数来包装查询。如果这就是你要做的。。请接受答案。
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
;