我有两个表,businesses
和items
。我试图根据updated_at
表格中items
列的最新项目更新来获取最近9家商家。
我相信这给了我最后9个business_id我需要的东西:
SELECT distinct business_id
FROM items
ORDER BY items.updated_at desc limit 9
所以我把它作为一个连接做了,并在选择中添加了另一个列,它会返回不同的结果。
SELECT b.*, i.updated_at as last_updated, i.business_id as business_id
FROM businesses AS b
INNER JOIN
(SELECT business_id, updated_at
FROM items
ORDER BY updated_at DESC
LIMIT 9) AS i
ON b.id = i.business_id
我绝对需要updated_at
表中的items
列,所以我知道实际日期。但是一旦我在select语句中添加了distinct,它会返回完全不同的结果,因为我假设行不再是不同的,因为id + updated_at使每一行都是唯一的。
按要求添加SQL架构: http://sqlfiddle.com/#!9/b44295
如果我们在上述数据的查询中执行limit 3
,则应返回:
---------------------------------------
| business_name | updated_at |
---------------------------------------
| Business Two | 2018-01-22 23:38:05 |
---------------------------------------
| Business One | 2018-01-02 23:38:05 |
---------------------------------------
| Business Five | 2018-01-01 23:39:51 |
---------------------------------------