使用UNION ALL或DISTINCT或NOT IN的正确方法

时间:2018-10-21 09:47:00

标签: mysql distinct union

我想我没有在这里使用最佳方法。我的目标是从两个单独的表中获取唯一记录,即     table2016和table2015

SELECT GROUP_CONCAT(coursecode) FROM table2016 WHERE regno = 'ABC/XY/DEF/12/155' AND (ca_score + exam_score) <= 39
UNION DISTINCT
SELECT GROUP_CONCAT(coursecode) FROM table2015 WHERE regno = 'ABC/XY/DEF/155' AND (ca_score + exam_score) <= 39

这就是我得到的:

GROUP_CONCAT(coursecode)
========================
EDM305,EDU313,EDU498
EDM305,EDU313,EDU497

我仍然有重复的记录。

或者,我尝试了NOT IN选项,但无济于事-当然,我知道很近

SELECT GROUP_CONCAT(coursecode) FROM table2016 WHERE regno = 'ABC/XY/DEF/12/155' AND (ca_score + exam_score) <= 39
NOT IN
(SELECT GROUP_CONCAT(coursecode) FROM table2015 WHERE regno = 'ABC/XY/DEF/155' AND (ca_score + exam_score) <= 39)

我可以使用一些指南。

2 个答案:

答案 0 :(得分:1)

您可以使用子查询来合并两个表中的行,然后对其进行串联:

SELECT GROUP_CONCAT(coursecode)
FROM (
    SELECT coursecode FROM table2016
    WHERE regno = 'ABC/XY/DEF/12/155' AND (ca_score + exam_score) <= 39
    UNION 
    SELECT coursecode FROM table2015 
    WHERE regno = 'ABC/XY/DEF/155' AND (ca_score + exam_score) <= 39
   ) s
WHERE coursecode NOT IN (SELECT coursecode 
                         FROM table2017
                         WHERE regno = 'ABC/XY/DEF/155' 
                           AND (ca_score + exam_score) >= 40);

答案 1 :(得分:0)

尝试以下方法:

select DISTINCT(subTable.column)
form (
    SELECT GROUP_CONCAT(coursecode) FROM table2016 WHERE regno = 'ABC/XY/DEF/12/155' AND (ca_score + exam_score) <= 39

    UNION DISTINCT

    SELECT GROUP_CONCAT(coursecode) FROM table2015 WHERE regno = 'ABC/XY/DEF/155' AND (ca_score + exam_score) <= 39
) as subTable