[英]SQL: SELECT one post by category if no posts select from another category only one query
Purpose : Every half-hour I query database to find a post that havn't published to publish,every time I query by different category,if no posts in this category,switch to next category. 目的 :每半小时查询一次数据库,以查找尚未发布的帖子,每次按不同类别查询时,如果该类别中没有帖子,请切换到下一个类别。 The if check done by SQL
由SQL完成的if检查
pseudo-code 伪码
SELECT FROM post WHERE post.cat_ID='7' AND post_date > '$last_query_time_cat_ID_7'
IF NO_POSTS_MATCH SELECT FROM post WHERE post.cat_ID='8' AND post_date>'$last_query_time_cat_ID_8'
...
pseudo explain :select one post of one category by its last query time of this category,if no new post of this category select from another category by its last query time. 伪解释 :如果没有该类别的新帖子在其最后一次查询时间从另一类别中选择,请按照该类别的最后一次查询时间来选择该类别的一个帖子。
My question: 我的问题:
Is there such SQL to do this work? 有这样的SQL可以完成这项工作吗?
This can be done by php to check if no posts return,then make another sql query.This could make many queries. 这可以通过php来检查是否没有帖子返回,然后进行另一个sql查询。这可以进行很多查询。
Somebody show me the sql-pseudo-code of this problem? 有人告诉我这个问题的sql-pseudo-code吗?
尝试使用CASE..WHEN ... ELSE语句。.请参见链接: http ://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html
Could look like this: 可能看起来像这样:
SELECT p.post_ID, p.cat_ID, p.post_date
FROM post p
JOIN (
SELECT cat_ID
,max(query_time) AS last_query
FROM post
WHERE cat_ID >= 7
GROUP BY 1
ORDER BY 1) l USING (cat_ID)
-- in some RDBMS you need ON l.cat_ID = p.cat_ID in the JOIN clause
WHERE p.post_date > l.last_query
ORDER BY p.cat_ID, p.post_date DESC
LIMIT 1; -- In T-SQL you need to write "SELECT TOP 1" instead
First get the timestamp of the last query per category in a subquery. 首先获取子查询中每个类别的最后一个查询的时间戳。 We are only interested in
cat_ID >= 7
我们只对
cat_ID >= 7
感兴趣
Join this to the base table and filter only rows with a later post_date
than last_query
per cat_ID
. 加入到这个基表并用过滤后仅排
post_date
比last_query
每cat_ID
。
Sort it by cat_ID
- you seem to want smallest cat_ID
first. 按
cat_ID
对其进行cat_ID
-您似乎首先想要最小的cat_ID
。 Secondary sort by post_date
descending, so the last post comes first. 二级排序按
post_date
降序排列,因此最后一个帖子排在第一位。
If there are none in cat_ID
7, cat_ID
8 will be first etc. Voila. 如果
cat_ID
7中没有,则cat_ID
8将是第一个,等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.