2016-03-21 6 views
0

İki tabloya, report_instance ve report_history (report_instance'ın birçok report_history) var. Her bir report_instance öğesine, report_history'nin ilk 10 kaydıyla katılmak istiyorum.Tablo 1'deki her bir kayıt nasıl tablo 2'nin birkaç kayıtlarına katılır?

Örnek:

report_instance r1 has 20 report_history 
report_instance r2 has 5 report_history 

sorgu bana ilk 10 kayıtların 20 report_history ve r2 5 report_history ile birlikte r1 katılma sonucunu vermelidir.

Benim Sorgu: Ben hata var

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

Neden bu soru, hata iletiniz MySQL'ten olduğunda sqlserver ile etiketleniyor? – Bohemian

+0

her raporun ilk 10 report_history olmasını istediğiniz anlamına gelir ... –

+0

@ZafarMalik evet –

cevap

0

feryat sorgu almak deneyin aşağıya örneğin

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

kullanımı

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); 

Veya, herhangi bir hata söyle var.

+0

ERROR 1064 (42000) alıyorum: SQL sözdiziminde bir hata var; Doğru sözdizimi için MySQL sunucu sürümünüze karşılık gelen elkitabını kontrol ediniz. Raporda '10 rhh.id 'den rapor_history' den raporda rhh.report_instance_id = ri.id sırasına göre rapor 'satırında' –

+0

'sorgusu var mı? –

+0

2. ve 3. sorgular sözdizimi hatası veriyor. –

0

aşağıdaki gibi son başına report_instance_id kayıtları almak için, değişkenleri kullanabilirsiniz:

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 
türetilmiş bir tablo report_instances masaya katıldı olarak

Yukarıdaki sorgu kullanabilirsiniz:

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