使用左连接时如何使用 order by
和 limit
过滤查询
store_profile
id + store_name
1 | Accessorize.me
2 | Active IT
3 | Edushop
4 | Gift2Kids
5 | Heavyarm
6 | Bamboo
store_fee
id + store_id + date_end
1 | 1 | 27-6-2013
2 | 2 | 29-8-2013
3 | 3 | 02-6-2013
4 | 4 | 20-4-2013
5 | 4 | 01-7-2013
6 | 4 | 28-9-2013
7 | 5 | 03-9-2013
8 | 6 | 01-9-2013
我之前的查询
$order_by_for_sort_column = "order by $column" //sorting column
$query = "SELECT * FROM store_profile sp LEFT JOIN store_fee sf ON (sf.store_id = sp.id) $order_by_for_sort_column";
我想要的是表store_fee
的order by id desc
和limit 1
,而不是整个查询。这样我就可以在 date_end
中获取每个商店的最新日期。
正如您所见,对于 store_id 4(store_fee),我有 3 个不同的日期,我只想获取最新的日期。
结果应该是这样的
1 | Accessorize.me 27-6-2013
2 | Active IT 29-8-2013
3 | Edushop 02-6-2013
4 | Gift2Kids 28-9-2013
5 | Heavyarm 03-9-2013
6 | Bamboo 01-9-2013
最佳答案
SELECT a.id, a.store_name, MAX(b.date_End) date_end
FROM store_profile a
LEFT JOIN store_fee b
ON a.ID = b.store_ID
GROUP BY a.id, a.store_name
但是,如果数据类型 date_End
列是 varchar,则上述查询将不起作用,因为它按字符对值进行排序,并且可能会错误地给出不需要的结果。 18-1-2013
大于 01-6-2013
。
要进一步了解有关联接的更多知识,请访问以下链接:
关于mysql - 使用左连接时使用 order by 和 limit 过滤查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14975240/