我有2个表,我的目标是只有一个SELECT查询返回项目名称,与该项目相关的子项目数以及最近添加的子项目是什么。
表-A
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| item_ID | int(11) | NO | PRI | NULL | auto_increment |
| item_name | varchar(300) | NO | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
表-B
+------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------+--------------+------+-----+---------+----------------+
| subitem_ID | int(12) | NO | PRI | NULL | auto_increment |
| subitem_relation | int(12) | NO | | NULL | |
| subitem_name | varchar(300) | NO | | NULL | |
| subitem_date | datetime | NO | | NULL | |
+------------------+--------------+------+-----+---------+----------------+
这是我在table_b中的数据:
+------------+------------------+--------------+---------------------+
| subitem_ID | subitem_relation | subitem_name | subitem_date |
+------------+------------------+--------------+---------------------+
| 1 | 1 | subitem a | 2014-06-09 10:51:20 |
| 2 | 1 | subitem b | 2014-06-10 05:21:52 |
| 3 | 2 | subitem c | 2014-06-16 05:12:10 |
| 4 | 1 | subitem d | 2014-06-18 06:42:14 |
| 5 | 2 | subitem e | 2014-06-23 19:33:08 |
| 6 | 2 | subitem f | 2014-07-02 12:30:25 |
| 7 | 2 | subitem g | 2014-07-04 21:52:40 |
+------------+------------------+--------------+---------------------+
这是我目前的查询:
SELECT
a.item_name,
COUNT(b.subitem_ID) as subitem_no,
b.subitem_name as most_recent_subitem
FROM
table_a as a
INNER JOIN
table_b as b
ON
a.item_ID = b.subitem_relation
GROUP BY
b.subitem_relation;
这就是结果:
+-------------+------------+---------------------+
| item_name | subitem_no | most_recent_subitem |
+-------------+------------+---------------------+
| first item | 3 | subitem a |
| second item | 4 | subitem c |
+-------------+------------+---------------------+
这将返回正确数量的子项,但它返回第一个相关子项而不是最新项。我需要以某种方式将table_b中的数据排序到ORDER BY subitem_date DESC,但不知道如何实现它。
我要找的结果是:
+-------------+------------+---------------------+
| item_name | subitem_no | most_recent_subitem |
+-------------+------------+---------------------+
| first item | 3 | subitem d |
| second item | 4 | subitem g |
+-------------+------------+---------------------+
答案 0 :(得分:2)
我会使用group_concat()
/ substring_index()
技巧:
SELECT a.item_name, COUNT(b.subitem_ID) as subitem_no,
substring_index(group_cooncat(b.subitem_name order by subitem_date desc
), ',', 1) as most_recent_subitem
FROM table_a a INNER JOIN
table_b b
ON a.item_ID = b.subitem_relation
GROUP BY a.item_ID;