mysql - 使用左连接时使用 order by 和 limit 过滤查询

标签 mysql sql select

使用左连接时如何使用 order bylimit 过滤查询

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_feeorder by id desclimit 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/

相关文章:

sql - 在 Select 中合并两个表 (SQL Server 2008)

MYSQL - 存储过程和准备好的语句处理引号

MySQL 日期范围 : ocurrences among same dates

mysql - 子表状态

mysql - 如何在 MySQL 上按字段识别排序记录间隙

list - 填充g:从查询中选择

MySQL Join 三个表返回多个结果

python - SQLAlchemy - 一次搜索三个表

php - 如何显示mysql数据库中的图像?当我尝试显示图像时,它仅显示该图像的名称

sql - Firebird isql : "there is no table XXXX in this database"