我制作了一个供稿墙,两个服务将帖子保存到同一个数据库表中。
一个发布服务的使用方式比另一个多,所以在墙上我想将每个服务限制在首页上的25个最新帖子(共50个)以获得相同的代表性。
这是我原来的,没有晚上的帖子:
$sql = "SELECT * FROM posts";
$sql .= " WHERE disq = 0";
$sql .= " AND approved = 1";
$sql .= " ORDER BY created_at DESC";
$sql .= " LIMIT 50";
然后我尝试通过服务来限制它们:
$sql_1 = "SELECT * FROM posts";
$sql_1 .= " WHERE disq = 0";
$sql_1 .= " AND approved = 1";
$sql_1 .= " AND source = 'TW'";
$sql_1 .= " ORDER BY created_at DESC";
$sql_1 .= " LIMIT 25";
$sql_2 = "SELECT * FROM posts";
$sql_2 .= " WHERE disq = 0";
$sql_2 .= " AND approved = 1";
$sql_2 .= " AND source = 'IG'";
$sql_2 .= " ORDER BY created_at DESC";
$sql_2 .= " LIMIT 25";
做类似
的事情$sql = $sql_1 UNION $sql_2;
似乎没有用,因为我看到的所有示例都在一堆查询结束时执行LIMIT。之后应该执行ORDER BY,按时间顺序对帖子进行重新排序,并使墙面混合服务。
赞赏MySQL帮助
答案 0 :(得分:1)
您可以在子查询中省略ORDER BY,并在联合之后最后执行此操作。
(
SELECT * FROM POSTS
WHERE disq = 0 AND approved = 1 AND source= 'TW'
LIMIT 25
)
UNION ALL
(
SELECT * FROM POSTS
WHERE disq = 0 AND approved = 1 AND source= 'IG'
LIMIT 25
)
ORDER BY created_at DESC
有关联合以及如何排序的更多信息,请参阅this MySQL documentation
答案 1 :(得分:1)
您需要将最近的25个项目与两个标准集分开,然后将它们放在一起并再次订购。
这将是这样的。您需要这些括号子查询,因为ORDER BY ... LIMIT
子句需要分别与每个子句相关联。
SELECT *
FROM
( SELECT *
FROM POSTS
WHERE disq = 1 AND approved = 1 AND source= 'TW'
ORDER BY created_at DESC
LIMIT 25
) A
UNION ALL
( SELECT *
FROM POSTS
WHERE disq = 1 AND approved = 1 AND source= 'IG'
ORDER BY created_at DESC
LIMIT 25
) A
ORDER BY created_at DESC, source
(disq, approved, source, created_at)
上的POSTS表上的索引将用于加速此查询。