在具有多个INNER JOIN的多列上使用GROUP BY

时间:2019-07-31 17:38:53

标签: mysql

我有一个简单的select查询,它将5个表连接在一起以获取信息。我想要两个不同表上两列的不同值,而不是两列中的值的不同组合。

社区表

+--------+----+------------------+-----------------+------+
| title  | id | shortdescription | longdescription | type |
+--------+----+------------------+-----------------+------+
| Sci-fi | 14 | Lorem ipsum      | Lorem ipsum     | mix  |
+--------+----+------------------+-----------------+------+

社区标签类别表:

+-----------+----------+
| community | category |
+-----------+----------+
|        14 |        5 |
|        14 |        9 |
|        14 |       17 |
|        14 |       18 |
+-----------+----------+

标签类别表

+-----------+----+
| category  | id |
+-----------+----+
| character |  5 |
| warning   |  9 |
| mention   | 17 |
| focus     | 18 |
+-----------+----+

社区标签表:

+-----------+-----+
| community | tag |
+-----------+-----+
|        14 | 136 |
|        14 | 137 |
|        14 | 138 |
|        14 | 139 |
+-----------+-----+

标签表:

+--------+-----+
|  name  | id  |
+--------+-----+
| sci-fi | 136 |
| space  | 137 |
| aliens | 138 |
| future | 139 |
+--------+-----+

这是我一直在尝试的查询:

SELECT c.title, c.id, c.shortdescription, c.longdescription, c.type, tc.category, t.name AS 'tag'
FROM Community c, CommunityTagCategories cc, TagCategory tc, CommunityTags ct, Tag t
WHERE c.id=cc.community
AND cc.category=tc.id
AND ct.tag=t.id
AND c.id=ct.community
AND c.id=14;

Community 14具有4 tag类别和4个标签,理想情况下,我希望返回4个结果。但是,它返回16个结果,因为它为我提供了标签类别和标签的所有可能组合。

我想查看的结果(社区表中的信息被截断为空格)

+-------------------------+--------------+-----------+
|    community columns    | tag category |    tag    |
+-------------------------+--------------+-----------+
| community info repeated | sci-fi       | character |
| community info repeated | space        | warning   |
| community info repeated | aliens       | mention   |
| community info repeated | future       | focus     |
+-------------------------+--------------+-----------+

如果我使用"GROUP BY t.id",则会返回4 tags,但它只会返回重复四次的一个标签类别(反之亦然,"GROUP BY tc.id")。

如果我在"GROUP BY tc.id, t.id"中使用逗号,那么它将再次返回16结果。

"GROUP BY tc.id AND t.id"不返回任何内容。

是否有一种方法只能针对4个标签类别和4个标签获得4行?

1 个答案:

答案 0 :(得分:0)

在标签和类别之间没有关系,实际上没有办法在子查询中制造“行号”之外的东西并使用它们作为联接条件,而在有更多查询时,您将不得不处理标签要比类别更多,或者类别要比标签更多(因为MySQL仍然没有FULL OUTER JOIN)。

这是更好的处理方式,因为可以对数据进行多次查询,然后在客户端处理演示文稿。