2016-10-23 138 views
3

考虑下表:选择所有多对多的关系

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中。我明白为什么会发生这种情况,但是有没有办法让每一个作者都可以使用?

回答

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; 
+0

是的,但只会得到所有的作者和他们的所有类型。我正在寻找所有作者及其所有类型,并在where子句中使用指定的类型。 – user2827048

+0

@ user2827048。 。 。你的问题澄清了这个问题。看我的编辑。 –

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" 
) 
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 
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