2012-08-24 42 views
3

我有我需要重複幾次工作查詢,但是我對UNION越來越語法錯誤ALL:無法聯合所有兩個等效查詢?

工作查詢:

set @num := 0, @group := ''; 

select person, `group`, age 
from 
(
    select person, `group`, age, 
     @num := if(@group = `group`, @num + 1, 1) as row_number, 
     @group := `group` as dummy 
    from mytable 
    order by `Group`, Age desc 
) as x where x.row_number <= 2; 

SQL FIDDLE

失敗UNION ALL(獲取語法錯誤):

set @num := 0, @group := ''; 
(
select person, `group`, age 
from 
(
    select person, `group`, age, 
     @num := if(@group = `group`, @num + 1, 1) as row_number, 
     @group := `group` as dummy 
    from mytable 
    order by `Group`, Age desc 
) as x where x.row_number <= 2; 
) 
UNION ALL 
(
select person, `group`, age 
from 
(
    select person, `group`, age, 
     @num := if(@group = `group`, @num + 1, 1) as row_number, 
     @group := `group` as dummy 
    from mytable 
    order by `Group`, Age desc 
) as x where x.row_number <= 2; 
) 

SQL FIDDLE

(在被聯合查詢只是出於測試目的,原始查詢的副本)

回答

1
set @num := 0, @group := ''; 

select person, `group`, age 
from 
(
    select person, `group`, age, 
     @num := if(@group = `group`, @num + 1, 1) as row_number, 
     @group := `group` as dummy 
    from mytable 
    order by `Group`, Age desc 
) as x where x.row_number <= 2 
UNION ALL 

select person, `group`, age 
from 
(
    select person, `group`, age, 
     @num := if(@group = `group`, @num + 1, 1) as row_number, 
     @group := `group` as dummy 
    from mytable 
    order by `Group`, Age desc 
) as x where x.row_number <= 2; 
1

取出最外面的括號。 SELECT語句應該以SELECT關鍵字開始,而不是開放的paren。