开发者

MySQL query for "Recent Activity"

开发者 https://www.devze.com 2023-02-15 04:10 出处:网络
I\'m creating a site where users can create photo albums, create events, upload videos etc. What I want to do is make a list of a given user\'s recent activity. Here\'s a small outline of my tables:

I'm creating a site where users can create photo albums, create events, upload videos etc. What I want to do is make a list of a given user's recent activity. Here's a small outline of my tables:

**videos**
id
user_id
uploaded

**albums**
id
user_id
created
updated

**comments**
id
user_id
date

Of course there are more fields in the table, and also more tables, 开发者_StackOverflow中文版but these should be enough to help me construct a query.

Now what I want to be output is a date, and the id for a given activity with these fields:

user_id, video_id, album_id, comment_id, date

Of course only one of the ID fields should be chosen, the rest should just be null, and the date should come from "uploaded" for videos, "updated" for albums and "date" for comments. The user_id should be selected in the query in a where statement so you get activity for a given user.

I've tried to construct this query but failed, quessing that COALESCE should be used for choosing the different timestamps but I just can't get around it.


Something like this?

(select user_id, id as video_id, NULL as album_id, NULL as comment_id, uploaded as date from videos)
UNION
(select user_id, NULL, id, NULL, uploaded from albums)
UNION
(select user_id, NULL, NULL, id, date from comments)

You can apply an ORDER BY clause after the whole thing, but WHERE conditions much be put inside the parenteses of each separate SELECT.

0

精彩评论

暂无评论...
验证码 换一张
取 消