Mysql:每只猫得到2个结果[一对多的关系]

时间:2012-09-25 11:38:42

标签: mysql sql performance join

我正在寻找获得结果的最佳方法,数据库包含超过100000个帖子和超过100000只猫

这是我的表格

-----------------
-  id   | name  |
-----------------
-  1    | x     |
-----------------
-  2    | y     |
-----------------

发表

--------------------------------------
-  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只猫中获取

,会发生什么

2 个答案:

答案 0 :(得分:1)

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子句使其成为可选项。

答案 1 :(得分:-3)

为了获得更好的性能,请使用exists子句

select * from posts p where exists
(select c.id from cats c)

检查sqlfiddle