来自多个语句的mysql select语句

时间:2014-09-18 12:24:28

标签: mysql

SET @row_number:=0;
SET @db_names:='';
SELECT @row_number:=CASE WHEN @db_names=app_id THEN @row_number+1 ELSE 1 END AS row_number,@db_names:=app_id AS db_names
FROM master_order 
ORDER BY app_id ;

当我运行此语句时,它会给我结果。

我希望它像

select *from (SET @row_number:=0;
SET @db_names:='';
SELECT @row_number:=CASE WHEN @db_names=app_id THEN @row_number+1 ELSE 1 END AS row_number,@db_names:=app_id AS db_names
FROM master_order 
ORDER BY app_id ) as temp

where row_number = 1;

我想选择重复列的第一行

1 个答案:

答案 0 :(得分:0)

您可以像这样简化:

SELECT * FROM master_order
ORDER BY app_id = '' DESC, app_id
LIMIT 1;

但是为了澄清如果这种简化无法实现它将如何运作,或者这样:

SET @row_number:=0;
SET @db_names:='';

select *from (
    SELECT @row_number:=CASE WHEN @db_names=app_id THEN @row_number+1 ELSE 1 END AS row_number,@db_names:=app_id AS db_names
    FROM master_order 
    ORDER BY app_id 
) as temp
where row_number = 1;

或者这个:

select *from (
    SELECT @row_number:=CASE WHEN @db_names=app_id THEN @row_number+1 ELSE 1 END AS row_number,@db_names:=app_id AS db_names
    FROM master_order 
    CROSS JOIN (SELECT @row_number := 0, @db_names := '') var_init
    ORDER BY app_id 
) as temp
where row_number = 1;