2016-03-21 82 views
0

我有两个名为report_instance和report_history的表(report_instance有很多report_history)。我想用report_history的前10条记录加入每个report_instance。如何将表1的每条记录加入表2的少量记录?

实施例:

report_instance r1 has 20 report_history 
report_instance r2 has 5 report_history 

查询应给我与前10个记录R 2与5 report_history 20 report_history和连接R1的结果。

我的查询:

select * 
from report_instances ri, report_history rh 
where ri.id in (select rhh.id 
       from report_history 
       where rhh.report_instance_id=ri.id limit 10); 

我得到了错误:

This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'

+0

当你的错误消息来自MySQL时,为什么这个问题用sqlserver标记? – Bohemian

+0

意味着你只需要每个report_intance的前10个report_history ...是它.. –

+0

@ZafarMalik是啊 –

回答

0

尝试获得波纹管查询,

SELECT TOP 10 {column-name} FROM {Table-name}; 

使用下面的例子,

select * 
from report_instances ri, report_history rh 
where ri.id in (select TOP 10 rh.id 
    from report_history 
    where rh.report_instance_id=ri.id); 

或者,

select * 
from report_instances ri, report_history rh 
where ri.id in (select rh.id 
    from report_history 
    where rh.report_instance_id=ri.id 
    order by rh.id desc limit 0,10); 

您有任何错误告诉我。

+0

我收到错误1064(42000):您的SQL语法错误;检查与您的MySQL服务器版本相对应的手册,以便在'10 rhh.id from report_history'附近使用正确的语法,其中rhh.report_instance_id = ri.id order by report'在第1行 –

+0

您检查那里的哪个查询? –

+0

第二个和第三个查询会引发语法错误。 –

0

可以使用变量,如下,以获得最新的每report_instance_id记录:

select *, 
     @rn := IF(@id = report_instance_id, @rn + 1, 
       IF(@id := report_instance_id, 1, 1)) AS rn 
from report_history 
cross join (select @rn := 0, @id := 0) as vars 
order by report_instance_id, id desc 

您可以使用上面的查询作为派生表连接到report_instances表:

select ri.*, rhd.* 
from report_instances as ri 
join (
    select *, 
      @rn := IF(@id = report_instance_id, @rn + 1, 
        IF(@id := report_instance_id, 1, 1)) AS rn 
    from report_history 
    cross join (select @rn := 0, @id := 0) as vars 
    order by report_instance_id, id desc 
) as rhd on ri.id = rhd.report_instance_id 
where rhd.rn <= 10 
相关问题