我有这样的查询
SELECT DISTINCT Id, AppStatusId,
IF ( (AppStatusId = 80),"1","2" ) as res
#(here i need res as "1" if AppStatusId = 80 for first 100 rows )
FROM App
WHERE
AppStatusId = 80
or
AppTypeId = 100
查询返回1000行,我想将条件为AppStatusId = 80的前100行的res列为1.我期待以下结果
Id, AppStatusId,res
14343 ,80 , ,1
2234 ,80 , ,1
3232 ,80 , ,1
..................
..................
..................
..................
8975, 80, ,1 # 100th row
3232, 80, ,0
102, 80, ,0
103, 80, ,0
..................
..................
222, 55, ,0 ( becuase of or AppTypeId = 100 in where condition)
答案 0 :(得分:0)
SELECT
Id
,AppStatusId
,if(AppStatusId = 80 AND RowNumber <= 100, 1, 0) as res
FROM
(
SELECT
*
,(@rn:= if(AppStatusId = 80, @rn + 1,@rn)) as RowNumber
FROM
App a
CROSS JOIN (SELECT @rn:=0) var
WHERE
a.AppStatusId = 80
OR a.AppTypeId = 100
ORDER BY
Id, AppstatusId...., whatever you want for the first 100 records
) t
这应该会让你到那里。它会生成一个行号,只有当AppStatusId = 80
加上它才会允许您选择记录的任何顺序,这样前100条记录中AppStatusId = 80
不必连续,如果你不这样做的话希望他们成为。如果您只是这样订购,它仍然有效。