I have 2 MySQL Tables:
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. (in that case a NULL for the state
and attend_time
would be good)
Here I rebuild the Data Structure: 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
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)
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
(未测试)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.