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 Fiddle

于 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 回答