从2 union sql语句中获取不同的记录

时间:2017-12-27 02:42:52

标签: mysql union distinct-values

我想寻求一些SQL专家的建议。

我编写了sql语句,用于从工作人员和校友表中获取作者姓名。一些作者的名字将在两个表格中。所以逻辑是如果作者姓名在员工中,则使用其他方式寻找校友表。

这是我的sql语句,看起来不错,但它显示了员工和校友表中的同一作者姓名。

SELECT DISTINCT AP.Author_name, P.people_id, P.Name, P.Journal_name, AP.Author_sortorder FROM  `Paper_Author` AS AP LEFT JOIN  `People` AS P ON ( AP.Author_id = P.people_id )  WHERE AP.Paper_id =3838

UNION  

SELECT DISTINCT AN.Author_name, N.People_id, N.Name, N.Journal_name, AN.Author_sortorder FROM  `Paper_Author` AS AN LEFT JOIN  `Alumni` AS N ON ( AN.Author_id = N.People_id )  WHERE AN.Paper_id =3838 ORDER BY Author_sortorder LIMIT 0 , 30

结果:

people_id--  Author_name--  Journal_name--  
    1        Name1              A1          
    2        Name2              B1          
    3        Name3              C1
    3        Name3              C1
    4        Name4              D
    4        Name4

预期结果:

 people_id--  Author_name--  Journal_name--  
    1           Name1            A1          
    2           Name2            B1          
    3           Name3            C1
    4           Name4            D 

2 个答案:

答案 0 :(得分:1)

这可以通过使用原始结果作为子查询的附加选择来解决

SELECT DISTINCT * FROM (
    SELECT DISTINCT AP.Author_name, P.people_id, P.Name, P.Journal_name, AP.Author_sortorder FROM  `Paper_Author` AS AP LEFT JOIN  `People` AS P ON ( AP.Author_id = P.people_id )  WHERE AP.Paper_id =3838

    UNION  

    SELECT DISTINCT AN.Author_name, N.People_id, N.Name, N.Journal_name, AN.Author_sortorder FROM  `Paper_Author` AS AN LEFT JOIN  `Alumni` AS N ON ( AN.Author_id = N.People_id )  WHERE AN.Paper_id =3838 ORDER BY Author_sortorder LIMIT 0 , 30
);

答案 1 :(得分:1)

此问题的难点在于您可能需要来自PeopleAlumni表的信息。我们想加入包含正确信息的单个表。以下查询的大部分复杂性在于创建一个包含每个人的正确元数据的表。

SELECT
    pa.Author_name,
    pa.Author_sortorder,
    t1.people_id,
    t1.Name,
    t1.Journal_name
FROM Paper_Author pa
LEFT JOIN
(
    SELECT people_id, Name, Journal_name, 0 AS source
    FROM People
    UNION ALL
    SELECT people_id, Name, Journal_name, 1
    FROM Alumni
) t1
    ON pa.Author_id = t1.people_id
INNER JOIN
(
    SELECT people_id, MIN(source) AS source
    FROM
    (
        SELECT people_id, 0 AS source
        FROM People
        UNION ALL
        SELECT people_id, 1
        FROM Alumni
    ) t
    GROUP BY people_id
) t2
    ON t1.people_id = t2.people_id AND
       t1.source = t2.source
WHERE
    pa.Paper_id = 3838;