我有一个页面,人们可以在其中发布评论
,还有一个页面,人们可以在其他人的个人资料上点击“关注
”(与LIKE
相同) Facebook
)
我想要一个 SELECT
查询来发布我的所有评论,但会按照以下方式对它们进行排序:
首先,打印您点击FOLLOW<的
.最新
个人的 2 条最新评论
(这些评论必须在本周本周
发布)/
其次,发布已发布的其余内容,按创建日期
排序
它们
(我使用的是 linux 时间
)
你能帮我进行 SQL 查询吗?
这是我当前的 SELECT
查询。它会在 create-date
之前提取所有评论:
SELECT
id, userID, text, createDate
FROM `comments` AS comment
WHERE (comment.refID = 0)
AND (comment.pageName = 'yard')
AND 1=1
ORDER BY comment.createDate DESC LIMIT 0, 20
“关注者
”表如下所示:
userID ownerID createDate
1 2 1439019657
1 4 1438940399
(用户 1 关注用户 2 和 4)
“评论
”表看起来像这样:
id userID pageName refID text createDate
220 1 yard 0 text1 1438030967
227 1 yard 0 text2 1438031704
228 1 yard 0 text3 1438031704
(userID
- 哪个用户发布评论。refID
- 始终为“0
”。pageName
- 始终“院子
”)
这种情况也是如此,如果我是用户 1,那么我希望看到用户 2 和 4 的最新 2 条评论(仅当它们是在最近周
中发表的)并且比查看(所有用户
)的所有其余评论按日期排序
(当然,没有我已经看到的一次)
最佳答案
您必须将其分成 2 个查询.. ..我猜测这里的一些表关系..
// get the last 2 comments from followed users..
SELECT *
FROM comments
WHERE userID IN (
SELECT ownerID
FROM followers
WHERE userID = ?
) ORDER BY createDate DESC
LIMIT 2
// then get the rest, removing already returned comments
SELECT *
FROM comments
WHERE id NOT IN (
-- either put the above query in here
-- or buuild an array of the 'id's when outputting the results above
-- and use that in here to prevent them being returned again
) ORDER BY createDate DESC
关于php - 根据条件从 2 个表中选择查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32045106/