COUNT(DISTINCT)子句中的WHERE子句

时间:2011-08-01 13:28:00

标签: mysql

这是Ryan Frank在forums.mysql.com上提出的问题,我也面临这个问题。

我在SELECT语句的开头有以下内容:

SELECT accounts.id, accounts.company, accounts.first, accounts.last,
COUNT(DISTINCT accounts_log.login_time) AS visits,
COUNT(DISTINCT accounts_log.ip_address) AS visitors,
COUNT(DISTINCT documents_log.access_time) AS docs,
MAX(accounts_log.login_time) AS login_time
FROM accounts

这将返回我需要的所有变量;但是,我想将使用COUNT(DISTINCT)的变量限制为日期范围。我不能在FROM子句后使用WHERE子句。例如:

FROM accounts
WHERE accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to'

不起作用,因为它不会给我所有帐户,就像我需要的那样。

我正在寻找类似的东西:

COUNT(DISTINCT accounts_log.login_time WHERE accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to') AS visits

P.S。我知道上面的内容不起作用,并且语法选项已用完。

2 个答案:

答案 0 :(得分:9)

SELECT accounts.id, accounts.company, accounts.first, accounts.last,
COUNT(DISTINCT case when accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to' then accounts_log.login_time else null end) AS visits,
COUNT(DISTINCT case when accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to' then accounts_log.ip_address else null end) AS visitors,
COUNT(DISTINCT case when accounts_log.login_time >='$search_from' AND accounts_log.login_time <='$search_to' then documents_log.access_time else null end) AS docs,
MAX(accounts_log.login_time) AS login_time
FROM accounts

答案 1 :(得分:0)

您可以将条件放在ON的{​​{1}}子句中:

LEFT JOIN

与其他表格相同。