简体   繁体   中英

How to select the title with the latest datetime?

I have these two tables in mysql:

posts (id)
post_titles (id, post_id, title, datetime, user_id)
post_contents (id, post_id, content, datetime, user_id)
post_statuses (id, post_id, status, datetime, user_id)

posts (id) == posts_titles (post_id)

In the post_titles and post_contents can be multiple entries for 1 posts (id) .

What i need, is to select the title which has the latest datetime. I would have to select it all by using the posts (id) . How could i do that?

EDIT: i need to select the latest title and latest content together or latest title, latest content and latest status.

Order by the column you are interested in (datetime in this case) and do a limit of 1. This will order the rows by datetime in descending order (newest will be first). And then limit 1 to just get the first row.

SELECT * FROM post_titles ORDER BY datetime DESC LIMIT 1;

Try this:

SELECT t.title, c.content
FROM post_titles t 
JOIN post_contents c ON t.post_id = c.post_id
WHERE 
t.datetime = 
    (SELECT MAX(x.datetime) FROM post_titles x WHERE t.post_id = x.post_id)
AND 
c.datetime = 
    (SELECT MAX(y.datetime) FROM post_contents y WHERE c.post_id = y.post_id);

I'm assuming that all the datetime are equal, because when you add something on the tables, the content are created at the same time.

EDIT: Now it doesn't matter if the datetime are equal. Check if it works.

To build on the answer from Mark S (I can't figure out how to quote or link to his answer...)

Since there are datetime fields on both post_title and post_contents tables, you'll have to specify which table's column to reference as you do the ordering, like this:

SELECT `title`, `content`
FROM `post_titles` t
    JOIN `post_contents` c USING (`post_id`)
ORDER BY t.datetime DESC
LIMIT 1

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.

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