Mysql在同一查询中计数和计数不同

时间:2013-09-08 21:18:31

标签: php mysql

我有以下2个表格:

user_table:

user_id
job_id
job_link

job_table:

job_id
click_ip
click_date

我必须为当前用户计算每个作业的不同点击次数和所有点击次数。任何人都能告诉我这是否可能与当前的表结构,并有一个答案。感谢。

我的当前查询也尝试使用内部联接:

SELECT  `user_id` , job.job_id AS job_id,  `job_link`, 
    COUNT( job.click_ip ) AS click_ip
FROM  `job` ,  `user` 
WHERE job.job_id = user.job_id
AND user.user_id =7
GROUP BY job_id

1 个答案:

答案 0 :(得分:2)

COUNT(DISTINCT字段)将完成这项工作:

SELECT user_id, 
    job.job_id AS job_id,
    job_link, 
    COUNT(job.click_ip) AS click_ip, 
    COUNT(DISTINCT job.click_ip) AS click_ip_distinct
FROM user JOIN job ON user.job_id = job.job_id
WHERE user.user_id =7
GROUP BY job_id

SQL小提琴:http://sqlfiddle.com/#!2/5e03e/2/0