有3个mysql表。
BOOKS have ID, AUTHOR1, AUTHOR2, PUBLISHER1, PUBLISHER2
AUTHORS have ID, WEBSITE
PUBLISHERS have ID, WEBSITE
并非所有出版商或作者都有网站。
我有一个查询,它返回给定图书ID的作者和发布者网站的匹配集。如果他们都有一个网站,这将意味着2行。
SELECT AUTHORS.WEBSITE as WEB1, PUBLISHERS.WEBSITE as WEB2
FROM BOOKS
LEFT OUTER JOIN AUTHORS ON (ID=AUTHOR1 OR ID=AUTHOR2)
LEFT OUTER JOIN PUBLISHERS ON (ID=PUBLISHER1 OR ID=PUBLISHER2)
WHERE BOOK.ID ='12345'
LIMIT 2
虽然这有效,但最终会在第一作者和出版商之前返回与第二作者和出版商匹配的行。可能基于字母顺序。
如何让此查询首先返回包含AUTHOR1和PUBLISHER1网站的行?
答案 0 :(得分:1)
我将它们视为单独的连接并使用COALESCE。
SELECT COALESCE(A1.WEBSITE, A2.WEBSITE) as WEB1,
COALESCE(P1.WEBSITE, P2.WEBSITE) as WEB2
FROM BOOKS B
LEFT OUTER JOIN AUTHORS A1 ON A1.ID=B.AUTHOR1
LEFT OUTER JOIN AUTHORS A2 ON A2.ID=B.AUTHOR2
LEFT OUTER JOIN PUBLISHERS P1 ON P1.ID=B.PUBLISHER1
LEFT OUTER JOIN PUBLISHERS P2 ON P2.ID=B.PUBLISHER2
WHERE B.ID ='12345'
答案 1 :(得分:0)
由于查询中没有order by子句,因此可以确保按字母顺序排序的结果只是简单的巧合。
反正
SELECT AUTHORS.WEBSITE as WEB1, PUBLISHERS.WEBSITE as WEB2
FROM BOOKS
LEFT OUTER JOIN AUTHORS ON (ID=AUTHOR1)
LEFT OUTER JOIN PUBLISHERS ON (ID=PUBLISHER1)
WHERE BOOK.ID ='12345'
UNION
SELECT AUTHORS.WEBSITE as WEB1, PUBLISHERS.WEBSITE as WEB2
FROM BOOKS
LEFT OUTER JOIN AUTHORS ON (ID=AUTHOR2)
LEFT OUTER JOIN PUBLISHERS ON (ID=PUBLISHER2)
WHERE BOOK.ID ='12345'
LIMIT 2