php - TABLE 的 SQL View 以及条件 COUNT 的记录

标签 php mysql sql sql-view

我正在尝试为特定查询创建一个 View ,如下所示。

4张 table

1. users(user_id, name, profilepic)
2. topics (topic_id, topic_by_id, topic_title, topic_data, timestamp)
3. likes (topic_id, liked_by_id, timestamp)
4. comments (topic_id, comment_by_id, comment_text, timestamp)

现在我已经为前两个表创建了一个 View 来获取数据。但下一步是获取点赞数和评论数,并查看当前用户是否对此主题点赞或评论。

topics 表是这里的主表,topic_by_idusers 表中的 user_id Liked_by_idcomment_by_id 也是 user_id

这就是我迄今为止为从前两个表中获取初始数据所做的工作。

CREATE VIEW TOPICS_VIEW AS 
SELECT topic.topic_id,
topic.topic_by_id AS TBYID,
topic.topic_title,
users.user_id AS UserID,
users.name, 
users.profiepic
FROM users,topic
WHERE user.user_id = topic.topic_by_id

现在如何编辑此查询以包含喜欢和评论的数量,并检查用户是否喜欢或评论了同一主题?

感谢任何帮助。

最佳答案

SELECT posts.post_id,
posts.post_creator_id AS Post_by_id,
users.user_id AS UserID,
users.f_name, 
users.profile_pic_url,
posts.post_title,
posts.post_text,
posts.post_image,
posts.post_location,
posts.post_timestamp,
posts.post_category,
posts.post_status,
(SELECT count(*) FROM post_likes WHERE users.user_id = post_likes.liked_user_id) as 
User_Liked,
(SELECT count(*) FROM post_comments WHERE users.user_id = 
post_comments.comment_creater_id) as User_Commented,
(SELECT count(*) FROM post_likes WHERE posts.post_id = post_likes.liked_post_id) as 
Total_Likes_On_Post,
(SELECT count(*) FROM post_comments WHERE posts.post_id = 
post_comments.comment_post_id) as Total_Comments_On_Post
FROM users,posts
WHERE users.user_id = posts.post_creator_id

关于php - TABLE 的 SQL View 以及条件 COUNT 的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59986693/

相关文章:

php - 专辑编码错误,简单的PHP

sql - 加入父 ID 的最佳方式

mysql - 在对象 View 中插入数据时出现重复的列名称

javascript - 数据从 PHP 到 JS - Google 日历 + CanvasJS

php - 在centos上从src代码编译PHP5.5失败

php - Mysql 选择(搜索)查询项目列表

php - UPDATE mysqli_query() 的正确语法/方法

mysql - 如果表中不存在参数,如何抛出错误处理程序?

mysql - 如何从 2 个时间表中获取所选时间?

sql - 在 postgresql 中四舍五入列值