我如何构造这种SQL查询

时间:2012-04-17 07:28:22

标签: php mysql database

我有以下数据库表 enter image description here

我想通过owner_id向用户显示通知1.通知显示告诉所有者两个用户(有ids 17和2)在{/ 1}} 1的帖子上发表了评论。 我尝试了以下查询,但它返回2行。如何构造查询以返回一行,因为我希望将一个帖子的通知一起返回?谢谢。

post_id

3 个答案:

答案 0 :(得分:1)

此代码不会为您提供commenters_id,而是为每个帖子回复的人数。 date将是有人回复该特定帖子的最后一次:

SELECT
    COUNT(DISTINCT commenters_id) AS commenter_count,
    owner_id,
    post_id,
    type,
    UNIX_TIMESTAMP(MAX(date_done)) AS date 
FROM notification
WHERE owner_id = '$user_id' AND commenters_id != '$user_id' 
GROUP BY owner_id, post_id, type
ORDER BY UNIX_TIMESTAMP(MAX(date_done)) DESC

答案 1 :(得分:1)

您可以使用GROUP_CONCAT(commenters_id)获取帖子的以逗号分隔的评论者ID列表。但是你必须通过post而不是commentor进行分组,所以查询看起来像是:

SELECT DISTINCT GROUP_CONCAT(commenters_id), id, owner_id, 
                post_id, type, UNIX_TIMESTAMP(date_done) AS date 
FROM notification 
GROUP BY post_id 
HAVING owner_id = '$user_id' AND commenters_id != '$user_id' 
ORDER BY date_done DESC

GROUP_CONCAT允许在需要时对数据进行一些处理,例如仅返回不同的值或对值进行排序。请参阅此处的完整文档:http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html#function_group-concat

答案 2 :(得分:0)

你的问题是你也选择了date_done列,这使得行是唯一的。 在这种情况下,DISTINCTGROUP BY都不允许对结果集进行分组。

将该列排除在此查询之外或使用MAX(date_done)

之类的内容

编辑: 等等......你已经只有两排,而不是四排?这不是你想要的结果吗?也许我误解了这个问题

相关问题