mysql UNION重复

时间:2016-08-11 15:34:25

标签: php mysql union


我正在使用这个mysql查询并对其进行排序,我添加了bool列 is_main (它来自主表)。结果是工作但我得到重复,因为 is_main 列..有什么解决方法吗? 查询:

SELECT 
    b.dateTime,
    a.id,
    a.jobName,
    a.is_main
FROM job_data a, data b
WHERE a.userEmail = b.userEmail AND a.userEmail = :email
UNION
SELECT 
    b.dateTime,
    b.id,
    b.jobName,
    b.is_main
FROM job_data a, data b
WHERE a.userEmail = b.userEmail AND a.userEmail = :email

ORDER BY is_main DESC


job_data表:

id | dateTime | jobName | is_main
1  | 00.00.00 | job1    | 0
2  | 00.00.00 | job2    | 0
3  | 00.00.00 | job3    | 0


数据表:

id | dateTime | jobName | is_main
1  | 00.00.00 | job1    | 1
2  | 00.00.00 | ---     | 1

输出如下:

job1  //this is not okay, because of duplicate job1
job1
job2 
job3 
_____
---  //this is perfect, because I want empty cell to show on top
job1
job2
job3

1 个答案:

答案 0 :(得分:0)

SELECT dateTime, id, jobName, max(is_main) from
( SELECT 
    b.dateTime,
    a.id,
    a.jobName,
    a.is_main
FROM job_data a, data b
WHERE a.userEmail = b.userEmail AND a.userEmail = :email
UNION
SELECT 
    b.dateTime,
    b.id,
    b.jobName,
    b.is_main
FROM job_data a, data b
WHERE a.userEmail = b.userEmail AND a.userEmail = :email

)
GROUP BY id