我正在寻找一些SQL查询专家的帮助。
我有一些困难时间来修复下面的sql语句中的问题。这是3个表的连接sql语句。我需要来自人和校友表的类似数据。并且两个表中的字段名称也相同。所以我的问题是 - 我是否可以在一个字段中获取类似的数据?
SELECT DISTINCT P.people_id, P.Name,P.Journal_name, N.People_id, N.Name, N.Journal_name
FROM `Paper_Author` AS A
LEFT JOIN `People` AS P ON ( A.Author_id = P.people_id )
LEFT JOIN `Alumni` AS N ON ( A.Author_id = N.People_id )
WHERE A.Paper_id =2067
ORDER BY A.Author_sortorder
LIMIT 0 , 30
当前结果的例如是:
Id-- Name-- Journal_name-- ID2-- Name-- Journal_name
1 Name1 A1 NULL NULL NULL
2 Name2 B1 5 Name10 NULL
3 Name3 C1 3 Name3 C1
预期结果:
Id-- Name-- Journal_name--
1 Name1 A1
2 Name2 B1
3 Name3 C1
5 Name10 NULL
我想知道我是否可以在单一领域获得类似的价值?例如:单个字段中的Journal_name都是什么?
答案 0 :(得分:1)
UNION应该适用于此任务。使用UNION语句,您可以在单个结果集中获得两个结果:
SELECT DISTINCT P.people_id, P.Name, P.Journal_name, AP.Author_sortorder
FROM `Paper_Author` AS AP
LEFT JOIN `People` AS P ON ( A.Author_id = P.people_id )
WHERE AP.Paper_id = 2067
UNION
SELECT DISTINCT N.People_id, N.Name, N.Journal_name, AN.Author_sortorder
FROM `Paper_Author` AS AN
LEFT JOIN `Alumni` AS N ON ( A.Author_id = N.People_id )
WHERE AN.Paper_id = 2067
ORDER BY Author_sortorder