2016-03-21 75 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 
相關問題