[英]What would be appropriate query in this scenario
Here is my scenario : 这是我的情况:
A user can post something on his profile, he can also share another user's post. 用户可以在自己的个人资料上发布内容,也可以分享其他用户的信息。 I want to select in a query every post and share he has done (ordered using datetime). 我想在查询中选择每个帖子并分享他已完成的操作(使用日期时间排序)。 I just can't find the appropriate query with my basic MySQL skills. 我只是用我的基本MySQL技能找不到合适的查询。 Help me find my way threw this! 帮我找出路吧! Cheers. 干杯。
id user_id content datetime
1 100 Loremipsum1 2013-03-04 19:35:02
2 200 Loremipsum2 2013-03-03 19:30:02
3 200 Loremipsum3 2013-03-01 19:25:02
id user_id target_id post_id datetime
1 100 200 2 2013-02-01 19:25:02
2 100 200 3 2013-02-01 19:24:02
3 200 100 1 2013-01-01 19:25:02
Let's say I would like to get every result for my user 100, the desired result would be 假设我想为我的用户100获得所有结果,则期望的结果是
id user_id content datetime
1 100 Loremipsum1 2013-03-04 19:35:02
2 200 Loremipsum2 2013-03-03 19:30:02
3 200 Loremipsum3 2013-03-01 19:25:02
because user 100 shared both post of user 200. 因为用户100共享了用户200的两个帖子。
EDIT : Some people think that I'm trying to be lazy and to have someone else doing my work for me. 编辑:有些人认为我正试图变得懒惰,并请其他人为我工作。 So here is where I am at the moment in my query. 因此,这是我目前在查询中的位置。
SELECT *
FROM user_stream
LEFT JOIN user_share
ON user_stream.user_id = user_share.user_id
WHERE user_id = 100
My problem here is that I need to select the content from my target_id not my user_id. 我的问题是我需要从target_id而不是user_id中选择内容。 But I have no idea of the target_id value. 但是我不知道target_id的值。 It could also be multiple value (if a user share multiple post). 它也可以是多个值(如果用户共享多个帖子)。
Not completely sure I understand what you're looking for, but to get a list of posts that a user has either created or shared, you can use UNION
to combine the results. 不能完全确定我了解您要查找的内容,但是要获取用户创建或共享的帖子列表,可以使用UNION
组合结果。 Something like this: 像这样:
SELECT *
FROM (
SELECT id, user_id, datetime, 'P' as type
FROM post
UNION
SELECT post_id, user_id, datetime, 'S' as type
FROM share
) t
WHERE user_id = 100
ORDER BY datetime
The type tells you whether it were a post or a share. 类型告诉您它是帖子还是共享。
Edit: Given your comments, then it looks like you just want the posts. 编辑:给定您的评论,然后看起来您只想要这些帖子。 Try this: 尝试这个:
SELECT *
FROM post
WHERE id IN (
SELECT id
FROM post
WHERE user_id = 100
UNION
SELECT post_id
FROM share
WHERE user_id = 100
)
ORDER BY datetime
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.