如何将表1的每条记录与表2的少量记录连接起来?

时间:2016-03-21 07:13:04

标签: mysql sql join

我有两个名为report_instance和report_history的表(report_instance有很多report_history)。我想将每个report_instance与report_history的前10条记录一起加入。

示例:

    enter cextern printf
section .data
fmt: db "number = %d", 10, 0 ; printf format string
fmt2: db " %s",10,0
fmt3: db " %s ", 10, 0
section .text
global main
main:
    push ebx      ; EBX is callee saved so we need to save it so that it
                  ; it can be restored when we RETurn from main
    xor ecx,ecx  ; ebx = 0 (counter)
L1:
    inc ecx
    xor eax,eax
    mov eax,ecx
    xor ebx,ebx
    xor edx,edx
    mov ebx,5
    idiv ebx
    cmp edx,0
    jz Fizz
    push ecx      ; 2nd parameter is our number to print
    push fmt      ; 1st parameter is the address of the format string
    call printf

    ;add sp, 8     ; We pushed 8 bytes prior to printf call, we must adjust the stack
                  ; by effectively removing those bytes.
           ; counter += 1
    cmp ecx,100
    jle L1        ; If counter is <= 100 go back and print again
    jmp end
Fizz:
    mov ebx,0x4669
    mov eax, 0x7A7A
    push ebx
    push eax
    push fmt2
    call printf
    pop eax
    pop ebx

    jmp L1
end:
    pop ebx       ; Restore EBX before exiting main per calling convention
    ret           ; RETurn from main will cause program to gracefully exit
                  ;     because we are linked to the C runtime code and main was
                  ;     called by that C runtime code when our program started.ode here

查询应该给我加入r1的结果,其中包含20个report_history的前10个记录,以及带有5个report_history的r2。

我的查询:

report_instance r1 has 20 report_history
report_instance r2 has 5 report_history

我收到了错误:

  

此版本的MySQL尚不支持'LIMIT&amp; IN / ALL / ANY / SOME   子查询'

2 个答案:

答案 0 :(得分: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);

你有任何错误告诉我。

答案 1 :(得分: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