我们网站的博客部分是wordpress。我想对主站点的主页做的是采取最新的博客文章摘录并将其放在主站点上,并附带博客站点上文章的链接。我正在尝试使SQL语句正常工作,我认为我有主要部分,但是想把它放在一个SELECT而不是两个SELECT中。
我有两个SELECT的原因是为了确保我获得该帖子的最新版本。首先我尝试修改SELECT以查看是否返回了一行 - 如果我这样做,我就完成了。如果没有行(帖子上没有修订版),请使用第二个SELECT语句。
SELECT TOP 1 * FROM wp_posts
WHERE post_type = 'revision'
AND post_parent IN (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3)
ORDER BY post_modified DESC
SELECT TOP 1 * FROM wp_posts
WHERE id IN (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3)
ORDER BY post_modified DESC
如何将这两个SELECT组合成一个SELECT,这样我就能确保始终获得一行(即最新的博客文章)
提前致谢。
答案 0 :(得分:1)
首先想到的是使用UNION然后你可以获取结果集的第一行:
SELECT TOP 1 * FROM wp_posts
WHERE post_type = 'revision'
AND post_parent IN (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3)
ORDER BY post_modified DESC
UNION
SELECT TOP 1 * FROM wp_posts
WHERE id IN (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3)
ORDER BY post_modified DESC
<强>更新强>
返回第一条记录的前一个sql的简单子选择:
SELECT TOP 1 * FROM (
SELECT TOP 1 * FROM wp_posts
WHERE post_type = 'revision'
AND post_parent IN (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3)
ORDER BY post_modified DESC
UNION
SELECT TOP 1 * FROM wp_posts
WHERE id IN (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3)
ORDER BY post_modified DESC)
答案 1 :(得分:1)
这对你有用吗?
SELECT TOP 1 wp_posts.*
FROM wp_posts, (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3) relations
WHERE
(post_type = 'revision' AND post_parent IN relations) OR
(id IN relations)
ORDER BY post_modified DESC
或者,
SELECT TOP 1 wp_posts.*
FROM wp_posts, (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3) relations
WHERE
(post_type = 'revision' AND post_parent IN relations AND id NOT IN relations) OR
(post_type <> 'revision' AND post_parent NOT IN relations AND id IN relations)
ORDER BY post_modified DESC
答案 2 :(得分:0)
SELECT TOP 1 * FROM wp_posts
WHERE (post_type = 'revision'
AND post_parent IN (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3))
OR (id IN (SELECT [object_id]
FROM wp_term_relationships
WHERE term_taxonomy_id = 3))
ORDER BY post_modified DESC