简体   繁体   中英

Mysql count and count distinct in same query

I have the following 2 tables:

user_table:

user_id
job_id
job_link

job_table:

job_id
click_ip
click_date

I have to count clicks both distinct and all clicks for each job for the current user. Can anybody tell me if this is possible with current table structure and have an answer to this. Thanks.

My current query is also tried with inner join:

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

COUNT(DISTINCT field) will do the job:

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 Fiddle here: http://sqlfiddle.com/#!2/5e03e/2/0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM