Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MySQL如何获取用户';什么样的活动?_Mysql - Fatal编程技术网

MySQL如何获取用户';什么样的活动?

MySQL如何获取用户';什么样的活动?,mysql,Mysql,我有这样的sql表,我想在用户页面中显示用户的活动,但我不知道如何编写有关此的查询,因此我的表如下所示: users id name posts id title description posts_likes id post_id user_id time posts_comments id post_id user_id time 现在我想向用户展示他们页面中的活动,如: 你对这篇文章发表了评论 或 你喜欢并评论了这篇文章 按时间排序,所以我写了一些这样的查

我有这样的sql表,我想在用户页面中显示用户的活动,但我不知道如何编写有关此的查询,因此我的表如下所示:

users
 id
 name

posts
 id
 title
 description

posts_likes
 id
 post_id
 user_id
 time

posts_comments
 id
 post_id
 user_id
 time
现在我想向用户展示他们页面中的活动,如: 你对这篇文章发表了评论你喜欢并评论了这篇文章 按时间排序,所以我写了一些这样的查询,但它有很多问题

SELECT posts.id , posts.title , posts_comments.comment , posts_likes.time , posts_comments.time
FROM posts 
JOIN posts_likes ON posts.id=posts_likes.post_id
JOIN posts_comments ON posts.id=posts_comments.post_id
WHERE posts_likes.user_id = 6 AND posts_comments.user_id =6
ORDER BY posts_likes.time, posts_comments.time DESC
所以当我使用这个查询时,会给我发帖子那个id=6的用户评论并喜欢,而从不给我看那些用户只评论用户只喜欢的帖子,所以如果有人知道我如何解决这个问题,我真的很感谢很多人sry为我的英语

试试这个:

SELECT posts.id , posts.title , posts_comments.comment , posts_likes.time , posts_comments.time
FROM posts 
LEFT JOIN posts_likes ON posts.id=posts_likes.post_id AND posts_likes.user_id = 6
LEFT JOIN posts_comments ON posts.id=posts_comments.post_id AND posts_comments.user_id = 6
WHERE  1
ORDER BY posts_likes.time DESC, posts_comments.time DESC

未测试

为其添加“日志”表。任何其他选项都会比较慢。所以你的意思是我应该创建另一个表,当用户评论或喜欢任何帖子时,请填充数据库?你可以尝试将where子句中的and改为or。您还可以合并您的posts\u likes和posts\u comments表,并添加一个布尔列,如果为true,则为comment,如果为false,则为like。@alishafie yes,随着数据库变得越来越大,你会发现自己的性能问题。伙计们,联合条款呢?tnx人,这是一个很好的方法来分离他们,但它给了我很多我不需要的记录,在大项目中,使处理过程变慢,我需要它只提供记录。。。