这是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。我知道上面的内容不起作用,并且语法选项已用完。
答案 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
与其他表格相同。