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 フィドル

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 フィドル

(UNIONed クエリは、テスト目的で元のクエリを複製したものです)

4

3 に答える 3

2

余分なブラケットがあります。

このSQLフィドルを参照してください

于 2012-08-24T20:00:49.450 に答える
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;
于 2012-08-24T20:05:08.090 に答える
1

最も外側のかっこを削除します。SELECT ステートメントは、開き括弧ではなく、SELECT キーワードで開始する必要があります。

于 2012-08-24T20:10:31.580 に答える