我有3个表,一个有'论文'(P),一个有'作者'(A),另一个有'authors__papers'(AP),这是一个包含一些其他值的查找表。我需要的是一个单独的查询,它给我一个列的作者姓名,其中AP = 0中的'is_contact_author'字段,另一列具有所有作者姓名(连接),其中AP.author_order>这些应按P.paper_id分组。
每个查询本身看起来像:
SELECT CONCAT(A.first_name,' ',A.last_name) as contact FROM authors A
join authors__papers AP on AP.author_id = A.author_id
WHERE AP.is_contact_author = 0
和
SELECT AP.paper_id, GROUP_CONCAT(CONCAT(A.first_name,' ',A.last_name) ORDER BY AP.author_order SEPARATOR ', ') as authors FROM authors A
join authors__papers AP on AP.author_id = A.author_id
WHERE AP.author_order > 0
GROUP BY AP.paper_id
每个都返回预期的单独结果。我尝试了一个子查询:
SELECT * FROM
(
SELECT CONCAT(A.first_name,' ',A.last_name) as contact FROM authors A
join authors__papers AP on AP.author_id = A.author_id
WHERE AP.is_contact_author = 1
) contact,
(
SELECT AP.paper_id, GROUP_CONCAT(CONCAT(A.first_name,' ',A.last_name) ORDER BY AP.author_order SEPARATOR ', ') as authors FROM authors A
join authors__papers AP on AP.author_id = A.author_id
WHERE AP.author_order > 0
GROUP BY AP.paper_id
) author_info
但是那个挂起(或者可能只是非常缓慢)。任何想法如何最好地从一个结果集中的两个查询获得此输出?每篇论文都有一个联系人和至少一个作者。联系人的author_order始终为0,作者为1到X.联系人的is_contact_author始终为1,如果有帮助或重要,则作者始终为0。
答案 0 :(得分:3)
当然它很慢,没有连接条件所以你正在进行笛卡尔连接。
试试这个:
SELECT author_info.paper_id, author_info.authors, contact.contact FROM
(
SELECT AP.paper_id as paper_id2,CONCAT(A.first_name,' ',A.last_name) as contact FROM authors A
join authors__papers AP on AP.author_id = A.author_id
WHERE AP.is_contact_author = 1
) contact
INNER JOIN
(
SELECT AP.paper_id, GROUP_CONCAT(CONCAT(A.first_name,' ',A.last_name) ORDER BY AP.author_order SEPARATOR ', ') as authors
FROM authors A
join authors__papers AP on AP.author_id = A.author_id
WHERE AP.author_order > 0
GROUP BY AP.paper_id
) author_info
ON(contact.paper_id = author_info.paper_id)
尝试使用正确的连接语法,这将帮助您避免这种错误。