使用 WHERE 而不是 LIMIT 进行限制
我想使用特定过滤器选择一些行,但如果我没有获得至少 40 行,则不进行限制。
这是一个伪示例:
SELECT * FROM `table`
WHERE
SUM(1) < 40 OR
`age` > 18
它与 LIMIT 类似,但 LIMIT 会考虑 WHERE 过滤器。如果我没有至少 40 行(但接受第一行),我想忽略过滤器。
我怎么做到这一点?
编辑:很多人怀疑我真正想要的是什么。
这是一个例子:
ID AGE
1 10
2 20
3 30
4 10
5 20
6 30
7 10
我想获得前两行。并且只有在至少两行之后,才获取与给定条件(WHERE)匹配的新行。
例如:我想要前 2 行还有年龄为 30 的行。结果将相当于:
ID AGE
1 10 <first>
2 20 <second>
3 30 <conditional>
6 30 <conditional>
I want to select some rows with a specific filter, but don't limit if I don't get, at least, 40 rows.
It's a pseudo-example:
SELECT * FROM `table`
WHERE
SUM(1) < 40 OR
`age` > 18
It's similar to LIMIT, but LIMIT will consider the WHERE filter ever. I want to ignore the filter if I don't have at least 40 rows (but accept the firsts rows).
How I do that?
Edit: a lot of people had doubts what I really wanted.
This is an example:
ID AGE
1 10
2 20
3 30
4 10
5 20
6 30
7 10
I want to get the first 2 rows EVER. And only after at least two rows, get new rows that match the given conditions (WHERE).
For example: I want the first 2 rows more rows whose age is 30. The result would be equivalent to:
ID AGE
1 10 <first>
2 20 <second>
3 30 <conditional>
6 30 <conditional>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用递增变量
@rownum
来模拟相同的功能。但是,这比limit
效率低得多,因为服务器将过滤掉的行放入内存中,并不断执行@rownum:=@rownum+1
计算。You can use an increasing variable
@rownum
to simulate the same functionality. However, this is much less efficient thanlimit
because the server brings the filtered-out rows into memory and continuously performs the@rownum:=@rownum+1
calculation.