我正在寻找最好的方法,用包含超过100000个帖子和100000多个猫的数据库来获得结果
这是我的桌子
猫
-----------------
- id | name |
-----------------
- 1 | x |
-----------------
- 2 | y |
-----------------Post
--------------------------------------
- id | cat_id | title | content |
--------------------------------------
- 1 | 1 | Post 1 | .. . . .|
--------------------------------------
- 2 | 1 | Post 2 | . . . . .|
--------------------------------------
- 3 | 2 | Post 3 | .. . . .|
--------------------------------------
- 4 | 1 | Post 4 | . . . . .|
--------------------------------------
- 5 | 1 | Post 5 | .. . . .|
--------------------------------------
- 6 | 2 | Post 6 | . . . . .|
--------------------------------------
- 7 | 1 | Post 7 | .. . . .|
--------------------------------------
- 8 | 2 | Post 8 | . . . . .|
--------------------------------------这是我想得到的结果
结果
--------------------------------------
-Postid | cat_id | title | content |
--------------------------------------
- 1 | 1 | Post 1 | .. . . .|
--------------------------------------
- 2 | 1 | Post 2 | . . . . .|
--------------------------------------
- 3 | 2 | Post 3 | .. . . .|
--------------------------------------
- 6 | 2 | Post 4 | . . . . .|
--------------------------------------这里是我刚刚编写的查询,但是我寻找最佳查询
SELECT
*
From
post
WHERE posts.cat_id = 1 limit 2
UNION
SELECT
*
From
post
WHERE posts.cat_id = 2 limit 2如果我想从一个查询中从10只猫那里得到什么?
发布于 2012-09-25 12:51:45
set @i := 0, @cat_id = 0;
select
post.id as Postid,
cat_id,
title,
content
from
post
inner join (
select
id,
case
when @cat_id = cat_id then @i := @i + 1
else @i := 1
end as i,
case when @cat_id != cat_id then @cat_id := cat_id end
from (
select id, cat_id
from post
-- where cat_id in (1, 2) uncomment this to limit categories
order by cat_id
) a
) s on s.id = post.id
where i <= 2
order by cat_id, post.id问题标题是每个类别,问题是10个类别,所以我评论了where子句,使它成为可选的。
发布于 2012-09-25 12:18:23
为了获得更好的性能,请使用exists子句
select * from posts p where exists
(select c.id from cats c)检查一下木琴。
https://stackoverflow.com/questions/12582162
复制相似问题