我正在使用php和mysql实现一个社交网站,我遇到了一个查询以获取通知。
我的通知表包含以下列:
user_id,post_id,type(定义天气评论(值2)或a 柱(1)),
状态( 0读取1未读取),msg(可选消息)
评论表格:
comment_id,user_id,post_id,comment,time,status
喜欢表:
user_id , post_id (可以在帖子表中存储post_id或 来自评论表的comment_id),类型(与通知类型相同) 所有三列都构成了一个独特的组合
现在我想获得通知输出,如:
notification_id |消息
1 | 3人喜欢你的帖子
2 | 2人评论了你的帖子
我创建了这个查询
SELECT `notification_id`,
CASE
WHEN `msg` IS NOT NULL THEN msg
WHEN `type`=1 THEN concat((SELECT count(user_id) from `likes` WHERE `post_id`=post_id AND `type`=1 AND `user_id`!='8'),' peoples Liked your post')
WHEN `type`=2 THEN concat((SELECT count(*) from (SELECT DISTINCT `user_id` FROM `comments` WHERE `post_id`=post_id AND `user_id`!='8') AS commenters),' peoples Commented on your post')
END AS message
FROM
`notifications` WHERE `user_id`='8' -- 8 is just a user_id I was testing on.
它似乎工作正常,直到我意识到价值观不正确,我很快意识到我的错误在
`post_id`=post_id
这一直是真的,所以所有的行都被计算在内。
我搜索了获取外部列值,但无法找到解决方案,能否帮助我如何实现它。
答案 0 :(得分:1)
您应该能够在查询中使用别名.. FROM
别名问题最有可能来自您的评论计数子查询..您可以将其重写为Select count(distinct user_id)
SELECT n.notification_id,
CASE
WHEN n.msg IS NOT NULL THEN n.msg
WHEN type=1 THEN concat((SELECT count(user_id) from likes AS l WHERE l.post_id=n.post_id AND l.type=1 AND l.user_id != n.user_id),' peoples Liked your post')
WHEN type=2 THEN concat((SELECT count(DISTINCT c.user_id) FROM comments AS c WHERE c.post_id=n.post_id AND c.USER_ID != n.user_id),' peoples Commented on your post')
END AS message
FROM
notifications AS n
WHERE
n.user_id='8' -- 8 is just a user_id I was testing on.
这是一个有用的sql小提琴示例DEMO
答案 1 :(得分:0)
尝试为您的表使用ALIAS名称。
例如:
FROM Notifications AS N
在这种情况下,您将为Notifications表提供别名。通过这种方式,您可以使用N.any_column_of_notifications_table来引用Notifications表的列。
使用此概念,您可以访问外部值,例如:
SELECT x.id, y.id
FROM Table_1 AS x,
INNER JOIN Tabel_2 AS y
WHERE x.user_id = y.user_id