[英]Select all many to many relationship
給出以下表格:
author
--------------
id int(11)
name varchar
author_type
---------------
id int(11)
type varchar
author_has_type
---------------
author_id int(11)
author_type_id int(11)
我正在嘗試編寫一個執行以下操作的查詢;
給定一個作者類型,它將顯示以下內容
author.name types
-The authors name- -All types of the author-
現在,我正在嘗試使用的查詢是
Select author.name, GROUP_CONCAT(author_type.type) as types
from author
left join author_has_type on author.id = author_has_type.author_id
left join author_type on author_has_type.author_type_id = author_type.id
where author_type.type = "EXAMPLE TYPE"
但是,當我這樣做時,它只返回group_concat中的給定類型。 我理解為什么會發生這種情況,但是有沒有辦法讓每一種類型的作者?
你需要一個group by
和刪除where
子句:
Select a.name, GROUP_CONCAT(t.type) as types
from author a left join
author_has_type aht
on a.id = aht.author_id left join
author_type t
on aht.author_type_id = t.id
group by a.name;
編輯:
我想你想要的是:
Select a.name, GROUP_CONCAT(t.type) as types
from author a left join
author_has_type aht
on a.id = aht.author_id left join
author_type t
on aht.author_type_id = t.id
group by a.name
having max(author_type.type = 'EXAMPLE TYPE') > 0;
您需要將分組添加到查詢中。 並且要限制要輸出哪些行,請使用帶有子查詢的HAVING。
SELECT author.name, GROUP_CONCAT(author_type.type) as types
FROM author
LEFT JOIN author_has_type on author.id = author_has_type.author_id
LEFT JOIN author_type on author_has_type.author_type_id = author_type.id
GROUP BY (author.name)
HAVING author.id IN (
SELECT id FROM author
JOIN author_has_type ON author.id = author_has_type.author_id
JOIN author_type ON author_has_type.author_type_id = author_type.id
WHERE author_type.type = "EXAMPLE TYPE"
)
SELECT author.name,
GROUP_CONCAT(author_type.type) as types
FROM author
LEFT JOIN author_has_type on author.id = author_has_type.author_id
LEFT JOIN author_type on author_has_type.author_type_id = author_type.id
(SELECT author.ID
FROM author
LEFT JOIN author_has_type on author.id = author_has_type.author_id
LEFT JOIN author_type on author_has_type.author_type_id = author_type.id
WHERE author_type.type = "EXAMPLE TYPE") temp
ON author.id=temp.id
SELECT
author.name,
result.types
FROM (
SELECT author.id, GROUP_CONCAT(types.type) AS types
FROM
author
INNER JOIN author_has_type
ON author.id = author_has_type.author_id
INNER JOIN author_type
ON author_has_type.author_type_id = author_type.id
AND author_type.type = "funny"
INNER JOIN author_has_type AS has_types
ON author.id = has_types.author_id
INNER JOIN author_type AS types
ON has_types.author_type_id = types.id
GROUP BY author.id
) AS result
INNER JOIN author
USING(id)
添加兩個內部聯接以過濾到要查找的類型。 然后使用接下來的兩個連接來獲取作者的所有類型。
將查詢分組並將其放入子查詢中。 在外部查詢中使用結果將authordata加入到結果中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.