这是非常基本的,我知道,但我经常会遇到这个问题。
表格
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 |
+-----+------------+----------+
类别结果无关紧要,一旦它按照我想要的方式工作,我就不会获取它。
答案 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