MySQL在带有类别的帖子上加入查询,每个帖子只返回一个结果

时间:2014-04-08 11:40:18

标签: mysql sql

这是非常基本的,我知道,但我经常会遇到这个问题。

表格

mysql> describe Posts;
+-----------+---------+------+-----+---------+----------------+
| Field     | Type    | Null | Key | Default | Extra          |
+-----------+---------+------+-----+---------+----------------+
| id        | int(11) | NO   | PRI | NULL    | auto_increment |
| Time      | int(11) | YES  | MUL | NULL    |                |
+-----------+---------+------+-----+---------+----------------+

mysql> describe PostCategories;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| pid      | int(11)     | YES  |     | NULL    |                |
| Category | varchar(20) | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

查询

SELECT P.id AS pid, P.Time, PC.Category FROM Posts P
LEFT OUTER JOIN PostCategories PC ON PC.pid = P.id
WHERE PC.Category IN('value1','value2') OR PC.Category IS NULL
ORDER BY P.Time DESC

返回

+-----+------------+----------+
| pid | Time       | Category |
+-----+------------+----------+
|   8 | 1396906256 | NULL     |
|   7 | 1396524835 | value1   |
|   7 | 1396524835 | value2   |
+-----+------------+----------+

期望的结果

我希望每个pid只给我一行。换句话说,无论Post有多少个类别,我都希望它只在结果数据集中产生一行。

+-----+------------+----------+
| pid | Time       | Category |
+-----+------------+----------+
|   8 | 1396906256 | NULL     |
|   7 | 1396524835 | value1   |
+-----+------------+----------+

类别结果无关紧要,一旦它按照我想要的方式工作,我就不会获取它。

2 个答案:

答案 0 :(得分:1)

SELECT P.id AS pid, MIN(P.Time) as first_post_time, MAX(PC.Category) as Category FROM Posts P
LEFT OUTER JOIN PostCategories PC ON PC.pid = P.id
WHERE PC.Category IN('value1','value2') OR PC.Category IS NULL
GROUP BY P.id
ORDER BY P.Time DESC

只需添加分组并计算时间和类别(使用最小或最大)

答案 1 :(得分:1)

使用Group By对帖子进行分组,您还可以使用mysql中的group_concat程序获取所有类别。

SELECT P.id AS pid, P.Time, GROUP_CONCAT(PC.Category, ' , ') FROM Posts P
LEFT OUTER JOIN PostCategories PC ON PC.pid = P.id
WHERE PC.Category IN('value1','value2') OR PC.Category IS NULL
GROUP BY P.pid
ORDER BY P.Time DESC