我有一个MySQL查询,它选择当前用户的朋友创建的内容,并按相反的时间顺序列出该内容。
SELECT node.nid AS nid,
node.created AS node_created
FROM node node
LEFT JOIN user_relationships user_relationships ON node.uid = user_relationships.requestee_id
LEFT JOIN users users_user_relationships ON user_relationships.requestee_id = users_user_relationships.uid
WHERE (node.status <> 0) AND (node.type in ('drigg', 'blog_post')) AND (user_relationships.requester_id = 1)
ORDER BY node_created DESC
如何“扩展”此查询,以便除了节点之外还列出注释?
这是评论表的结构:
现在,查询抓取了当前用户与好友的所有“节点”。我希望它还能抓住当前用户与好友的所有评论。然后我想根据它们的创建日期以DESC顺序列出这些节点和注释。
看来我需要在select语句中添加更多内容,但我不确定是什么。
答案 0 :(得分:1)
您可以使用UNION ALL来合并两个查询的结果:
SELECT nodeid, commentid, created FROM (
SELECT node.nid AS nodeid, NULL as commentid, node.created AS created
FROM node node
LEFT JOIN user_relationships user_relationships ON node.uid = user_relationships.requestee_id
LEFT JOIN users users_user_relationships ON user_relationships.requestee_id = users_user_relationships.uid
WHERE (node.status <> 0) AND (node.type in ('drigg', 'blog_post')) AND (user_relationships.requester_id = 1)
UNION ALL
SELECT NULL as nodeid, comment.cid AS commentid, comment.timestamp AS created
FROM node node
LEFT JOIN user_relationships user_relationships ON node.uid = user_relationships.requestee_id
LEFT JOIN users users_user_relationships ON user_relationships.requestee_id = users_user_relationships.uid
WHERE (node.status <> 0) AND (node.type in ('drigg', 'blog_post')) AND (user_relationships.requester_id = 1)
)
ORDER BY created DESC
答案 1 :(得分:1)
现在,查询抓取了当前用户与好友的所有“节点”。我希望它还能抓住当前用户与好友的所有评论。然后我想根据它们的创建日期以DESC顺序列出这些节点和注释。
使用:
SELECT n.nid,
COALESCE(c.timestamp, n.created) AS coalesced_timestamp,
c.comment
FROM NODE n
LEFT JOIN USER_RELATIONSHIPS ur ON ur.requestee_id = n.uid
LEFT JOIN USERS u ON u.uid = ur.requestee_id
LEFT JOIN COMMENT c ON c.uid = u.uid
AND c.nid = n.nid
WHERE n.status <> 0
AND n.type in ('drigg', 'blog_post')
AND ur.requester_id = 1
ORDER BY coalesced_timestamp DESC
那是based on the ERD listed here。
使表名别与表名本身相同或更长没有多大意义。