gpt4 book ai didi

mysql - 如何从 user 和 usermeta 表中选择最后一个用户信息?

转载 作者:可可西里 更新时间:2023-11-01 06:36:21 26 4
gpt4 key购买 nike

我使用的是 mysql,我有两个表格如下:

User:
user_id - user_name - phone

UserMeta:
user_meta_id - user_id - meta_key - meta_value - meta_date

我有如下一些记录:

user_id: 23  
meta_key: gender
meta_value: male
meta_date: 1534533650



user_id: 23
meta_key: city
meta_value: london
meta_date: 1534533650



user_id: 23
meta_key: name
meta_value: jack
meta_date: 1534533650



user_id: 25
meta_key: name
meta_value: Jamie
meta_date: 1534593881

user_id: 25
meta_key: gender
meta_value: male
meta_date: 1534593881

user_id: 23
meta_key: gender
meta_value: female
meta_date: 1534595971

user_id: 23
meta_key: city
meta_value: liverpool
meta_date: 1534595971

And ...

我需要获取所有用户信息 (user_id = 23) 并注册了最新更改,例如:

user_id: 23  
meta_key: name
meta_value: Jamie
meta_date: 1534533650

user_id: 23
meta_key: city
meta_value: liverpool
meta_date: 1534595971

user_id: 23
meta_key: gender
meta_value: female
meta_date: 1534595971

这个操作的查询很复杂,我很困惑,请帮助我,
我用了这个但没有得到正确的结果:

    "SELECT kmu.*
FROM user_meta kmu
INNER JOIN
(SELECT `meta_key`, `meta_value`, MAX(`meta_date`) AS MaxDateTime
FROM user_meta
GROUP BY meta_key) groupedtt
ON user_id=:id
AND kmu.meta_key = groupedtt.meta_key
AND kmu.meta_date = groupedtt.MaxDateTime";

最佳答案

您可以使用以下内容:

SELECT `user`.*, user_meta.meta_key, user_meta.meta_value, user_meta.meta_date 
FROM `user` INNER JOIN (
SELECT user_id, meta_key, MAX(meta_date) AS meta_date
FROM user_meta
GROUP BY user_id, meta_key
) meta_select ON `user`.user_id = meta_select.user_id
INNER JOIN user_meta ON meta_select.meta_key = user_meta.meta_key
AND meta_select.user_id = user_meta.user_id
AND meta_select.meta_date = user_meta.meta_date
WHERE `user`.user_id = 23

demo: https://www.db-fiddle.com/f/euqvGNW6PguCG495Yi9dTa/1

关于mysql - 如何从 user 和 usermeta 表中选择最后一个用户信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51933861/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com