简体   繁体   English

从具有最新条目的另一个表中选择值

[英]Select values from another table with most recent entry

I have 2 MySQL Tables: 我有2个MySQL表:

Table with all Events 包含所有事件的表

+----+---------------------+
| id | Eventtitle          |
+----+---------------------+
|  1 | Event 1             |
|  2 | Event 2             |
|  3 | Event 3             |
|  4 | Event 4             |
+----+---------------------+

Table with user attend statuses - Users can change their status multiple times. 具有用户出席状态的表-用户可以多次更改其状态。 Every time they change it, a new entry is inserted into the table 每次更改时,都会在表中插入一个新条目

+----+------------+----------+---------+---------------------+
| id | event_id   | user_id  | status  | attend_time         |
+----+------------+----------+---------+---------------------+
|  1 | 1          | 2        | 1       |2013-07-03 15:34:02  |
|  2 | 1          | 2        | 2       |2013-08-03 19:01:02  |  <--
|  3 | 3          | 1        | 1       |2013-07-03 15:34:02  |
|  4 | 4          | 4        | 3       |2013-07-03 15:34:02  |
|  5 | 4          | 6        | 2       |2013-07-03 15:34:02  |
|  6 | 4          | 6        | 1       |2013-07-03 18:55:02  |  <--
+----+-----------------------+---------+---------------------+

Now I want all events listed and additionally the most recent attend state and attend_time of the currently logged in user (for example user_id 2 oder 54) - IF he is not in the attend table i still need an entry of the event. 现在,我要列出所有事件,并希望列出当前登录用户的最新出席stateattend_time (例如,user_id 2或54)-如果他不在出席表中,我仍需要该事件的条目。 (in that case a NULL for the state and attend_time would be good) (在这种情况下, stateattend_time为NULL会很好)

Here I rebuild the Data Structure: http://sqlfiddle.com/#!2/c1b3f 在这里,我重建数据结构: http : //sqlfiddle.com/#!2/c1b3f

IF there is no way on how to get the result with MySQL - I will try to get it with PHP 如果无法通过MySQL获得结果-我将尝试通过PHP获得结果

Try something like this: 尝试这样的事情:

SELECT s.id, eventtitle, status, attend_time
FROM events e
JOIN status s ON e.id = s.event_id
WHERE user_id = 2 AND attend_time = (SELECT MAX(attend_time) FROM status
                                       WHERE user_id = 2)

SQLFiddle SQLFiddle

Or: 要么:

SELECT s.id, eventtitle, s.status, s.attend_time
FROM events e
JOIN status s ON e.id = s.event_id
LEFT JOIN status s2 ON s.attend_time < s2.attend_time
WHERE s.user_id = 2 AND  s2.attend_time IS NULL

SQLFiddle SQLFiddle

(未测试)

SELECT a.id, eventtitle, status, attend_time FROM events b JOIN status a ON b.id = a.event_id WHERE user_id = 2 order by attend_time desc

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

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