我需要从我的数据库中分页帖子,我写下一个查询:
SELECT posts.ID, posts.date, comments.name, comments.value
FROM posts
INNER JOIN comments
ON comments.ID = posts.ID
INNER JOIN relations
ON relations.ID = posts.ID
WHERE type_rel=1 AND status_post=1 AND
LIMIT 0,10
问题出在LIMIT句子中,我只需要限制“帖子”表。
评论表有很多行,如果我把限制放在“0,10”中,“posts”表限制为10个帖子,但评论表也限制为10个。
有人能解决我的问题吗?我在PHP查询中使用它。
抱歉我的英语不好,提前谢谢。
答案 0 :(得分:6)
您可以使用子查询来限制结果集,然后加入:
SELECT
posts.ID,
posts.date,
comments.name,
comments.value
FROM
(SELECT * FROM posts WHERE status_post = 1 LIMIT 0,10) posts
LEFT JOIN
comments
ON comments.ID = posts.ID
LEFT JOIN
relations
ON relations.ID = posts.ID AND relations.type_rel = 1
从评论中,索引文件中的查询是错误的,这是正确的:
SELECT
wp_posts.ID,
wp_posts.post_date,
wp_postmeta.meta_key,
wp_postmeta.meta_value
FROM (SELECT * FROM wp_posts WHERE post_status="publish" AND post_type="post" LIMIT 0,2) wp_posts
LEFT JOIN wp_postmeta
ON wp_postmeta.post_id = wp_posts.ID
LEFT JOIN wp_term_relationships
ON wp_term_relationships.object_id = wp_posts.ID
AND wp_term_relationships.term_taxonomy_id=2
示例结果here,你可以看到你有两个帖子,id 1和5。
如果您想保留term_taxonomy_id = 2
使用此帖子的帖子:
SELECT
wp_posts.ID,
wp_posts.post_date,
wp_postmeta.meta_key,
wp_postmeta.meta_value
FROM (
SELECT *
FROM wp_posts
JOIN wp_term_relationships
ON wp_term_relationships.object_id = wp_posts.ID
AND wp_term_relationships.term_taxonomy_id = 2
WHERE post_status="publish" AND post_type="post" LIMIT 0,2) wp_posts
LEFT JOIN wp_postmeta ON wp_postmeta.post_id = wp_posts.ID
Example here,帖子ID为5和7,限制0,1仅返回5.
答案 1 :(得分:0)
您只能限制从posts表返回的行
SELECT posts.ID, posts.date, comments.name, comments.value
FROM (select * from posts limit 0,10) posts
INNER JOIN comments
ON comments.ID = posts.ID
INNER JOIN relations
ON relations.ID = posts.ID
WHERE type_rel=1 AND status_post=1
答案 2 :(得分:0)
您可以尝试:
SELECT a.ID, a.date, a.name, a.value
FROM (
SELECT posts.ID, posts.date, comments.name, comments.value,
@post_rank := IF(@current_post = posts.ID, @post_rank + 1, 1) AS post_rank,
@current_post := posts.ID
FROM posts
INNER JOIN comments
ON comments.ID = posts.ID
INNER JOIN relations
ON relations.ID = posts.ID
WHERE type_rel=1 AND status_post=1
ORDER BY posts.ID DESC )a
WHERE a.post_rank <= 10