我有一个页面,人们可以在其中发布comments
,也可以在其他人的个人资料中点击"follow
"(与Facebook
上的LIKE
相同(
我想让SELECT
查询发布我的所有评论,但会按照以下方式订购:
首先,打印您单击FOLLOW
的lastest
人员的2个最新的comments
(他们必须已发布此week
(。
其次,张贴其余张贴的,order
他们通过create-date
(我用的是linux time
(
你能帮我做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
"followers
"表如下:
userID ownerID createDate
1 2 1439019657
1 4 1438940399
(用户1在用户2和4之后(
"comments
"表看起来像这样:
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
-始终"yard
"(
在这种情况下,如果我是1号用户,那么我希望看到用户2和4的最新2条评论(仅当它们是在最后一个week
中生成的(,并且希望看到(all users
的(order by date
的所有其他评论(当然,没有我已经看到的一次(
您将不得不将其拆分为两个查询。。我在猜测这里的一些表关系。。
// 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
(select com.userID,com.page,com.text
from followers as fol
JOIN comments as com
ON fol.ownerId=com.userId
where
(
from_unixtime(com.createDate) BETWEEN
(
UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL -14 DAY) AND UNIX_TIMESTAMP(NOW())
)
Order BY com.createDate desc
)
Union
(select com.userID,com.page,com.text
from comments as com
where com.id NOT In
(select com.id
from followers as fol
JOIN comments as com
ON fol.userId=com.userId
where
(
from_unixtime(com.createDate) BETWEEN
(
UNIX_TIMESTAMP(DATE_ADD(CURDATE(),INTERVAL -14 DAY) AND UNIX_TIMESTAMP(NOW())
)
)
Order BY com.createDate desc
)
解释:使用并集将两个查询合并为一个查询。
- Select语句将为所有数据追随者提供注释。这是使用Join完成的
- 选择语句以获取所有其他注释,然后是上述第一个查询的注释
唯一不清楚的是你是如何决定用户已阅读评论(信息不足(