我一直在尝试从一个表中选择所有内容,然后针对每个结果从另一表中选择仅使用MySQL的一个最新结果。
第一个表是标准表,带有AI ID和文本名称
users
+----+-------+
| id | name |
+----+-------+
| 1 | John |
| 2 | Peter |
+----+-------+
然后是第二个具有AI id,int user_id,文本操作和日期时间日期的
actions
+----+---------+--------+------------+-----+
| id | user_id | action | date | str |
+----+---------+--------+------------+-----+
| 7 | 2 | drink | 2019-01-10 | 5 |
| 6 | 1 | sleep | 2019-02-14 | -2 |
| 5 | 2 | walk | 2019-04-24 | 4 |
| 4 | 1 | jump | 2019-03-14 | 3 |
| 3 | 2 | talk | 2019-04-30 | -8 |
| 2 | 2 | train | 2019-04-14 | -1 |
| 1 | 1 | drive | 2019-04-01 | 1 |
+----+---------+--------+------------+-----+
因此,现在我想从table_users
中选择所有内容,并为每个找到的行搜索table_actions
并根据ID或日期仅查找最新的行。
所以它看起来像这样(按ID)
[0] => ['user_id'] = 1
['name'] = John
['action'] = sleep
['date'] = 2019-02-14
['str'] = -2
[1] => ['user_id'] = 2
['name'] = Peter
['action'] = drink
['date'] = 2019-01-10
['str'] = 5
或类似的
[0] => ['id'] = 1
['name'] = John
['table_actions'] => ['id'] = 6
['user_id'] = 1
['action'] = sleep
['date'] = 2019-02-14
['str'] = -2
这听起来很简单,但是我尝试了很少的事情,却没有任何效果。收盘时有类似的提示(我手上没有确切的版本,只是想起了脑袋):
SELECT users.*, actions.*
FROM users
LEFT JOIN actions ON users.id = (
SELECT user_id FROM actions
WHERE users.id = actions.user_id
LIMIT 1
)
GROUP BY actions.user_id
这样,我将从users
获得所有结果,然后为每个从actions
获得一个结果,但是来自actions
的结果将不是最新的,显然它将它喜欢,我尝试了MAX(actions.id),但是我没有运气。
有人知道解决方案吗?现在,我必须从users
中获取所有信息,并为每个结果在我的php代码中进行另一个查询,我觉得有一种优雅而又快捷的方法。
答案 0 :(得分:0)
使用此查询:
select
user_id,
max(date) date
from actions
group by user_id
您为每个用户获取最新的date
,然后必须将其加入2个表:
select
u.id, u.name, a.id, a.action, a.date, a.str
from users u
inner join actions a on a.user_id = u.id
inner join (
select
user_id,
max(date) date
from actions
group by user_id
) g on g.user_id = a.user_id and g.date = a.date
如果要按ID而不按日期获取最新结果:
select
u.id, u.name, a.id, a.action, a.date, a.str
from users u
inner join actions a on a.user_id = u.id
inner join (
select
user_id,
max(id) id
from actions
group by user_id
) g on g.user_id = a.user_id and g.id = a.id