选择所有多对多的关系

时间:2016-10-23 23:15:43

标签: mysql sql

鉴于以下表格:

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中的给定类型。我理解为什么会发生这种情况,但有没有办法让每一种类型的作者?

4 个答案:

答案 0 :(得分:0)

您需要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;

答案 1 :(得分: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"
)

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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加入到结果中。

Example