简体   繁体   English

mysql连接问题,以一对多关系连接最新记录

[英]mysql join question, joining newest record in a one to many relationship

I have a simple (hopefully) SQL question for you, any help would be much, much appreciated :). 我对您有一个简单的(希望)SQL问题,任何帮助将不胜感激:)。

I have two tables which I would like to join. 我有两个表要加入。

One Is Users, lets say it's called users 一个是用户,可以说它叫做用户

One is a kind of history of that user, lets say its called users_history. 一个是那个用户的一种历史,可以说它叫做users_history。

The relationship of these two is a one users to many users_history relationship. 这两个的关系是一个用户到许多users_history的关系。

What I'd like to do is a query which joins the tables and joins the newest record in users_history onto each user. 我想做的是一个查询,该查询将这些表联接在一起,并将users_history中的最新记录联接到每个用户上。

Lets say the tables are like this, I'm simplifying for conciseness. 可以说表格是这样的,为简洁起见,我正在简化。

users 用户

  • id ID
  • name 名称

users_history users_history

  • id ID
  • user_id 用户身份
  • date 日期

The date is formatted YYYYMMDD. 日期的格式为YYYYMMDD。

The end result is I'd like to be able to pull out all of the users who don't have a users_history record for today, for example today is 20101021. 最终结果是,我希望能够撤出今天没有users_history记录的所有用户,例如今天是20101021。

Any help would be very gratefully received! 任何帮助将不胜感激! :) :)

Try 尝试

SELECT MAX(users_history.date), users.name FROM users 
LEFT JOIN users_history ON users.id = users_history.user_id
GROUP BY users_history.user_id
HAVING MAX(users_history.date) < CURDATE()

If you dont want users who doesnt have eny users_history records in the resultset, change the "LEFT JOIN" to a "JOIN" 如果您不希望结果集中没有eny users_history记录的用户,请将“ LEFT JOIN”更改为“ JOIN”

If all you really want is finding the users without a user_history entry for today, you can use a subquery like so: 如果您真正想要的是找到今天没有user_history条目的用户,则可以使用如下子查询:

SELECT * FROM users WHERE NOT EXISTS (SELECT id FROM users_history WHERE user_id = users.id AND `date` = DATE(NOW()));

IMHO, this is more readable than a join and some filtering in your host language. 恕我直言,这比连接和使用宿主语言进行的过滤更具可读性。

edit: Judging from your date format description, you probably use a varchar column to store the date. 编辑:从日期格式说明来看,您可能使用varchar列来存储日期。 In that case, replace DATE(NOW()) with the appropriate string representation for "today" - though I'd recommend changing the column type to a date/time type . 在这种情况下,请用“今天”的适当字符串表示形式替换DATE(NOW()) -尽管我建议将列类型更改为日期/时间类型

pull out all of the users who don't have a users_history record for today, for example today is 20101021. 抽出今天没有users_history记录的所有用户,例如今天是20101021。

select
 u.*
from
 users u
left outer join users_history uh on 
  u.id = uh.user_id and uh.history_date = curdate()
where
 uh.user_id is null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM