mysql中条件计数_MySQL中的计数或条件限制

总之,执行此操作的方法是运行两个查询并获取集合的UNION.而已.这样做的确很少有性能损失,因为如果结果中确实有超过5行,则已经需要第一组(可以产生> 5行).

详细 – 原始答案如下

为了说明,我只使用同一样本表中的2列,而不是使用2个数据集,查询将在下面进一步显示:

drop table if exists tbl1;

create table tbl1 (

id int,

name varchar(100),

distance1 float,

distance2 float

);

insert tbl1 values

( 3 , 'Earl of Sandwich ', 0.3, 0.1),

( 4 , 'Nails ''n More ', 0.8, 0.2),

( 22 , 'City Hotel ', 1.7, 1.7),

( 5 , 'Mighty Medicine ', 2.1, 0.5),

( 25 , 'Wonder Wings ', 2.5, 2.1),

( 6 , 'Jean Warehouse ', 2.7, 0.7),

( 9 , 'Ship Safe & Speedy ', 2.9, 0.9),

( 2 , 'Bagel Bonus ', 4.1, 1.2);

以及查询和结果:

/* query 1 */

select id, name, distance1

from (

select *

from tbl1

where distance1 <= 2.0

order by distance1) a

union

select id, name, distance1

from (

select *

from tbl1

order by distance1

limit 5) b;

/* result 1 */

id;name;distance1

3;Earl of Sandwich ;0.3

4;Nails 'n More ;0.8

22;City Hotel ;1.7

5;Mighty Medicine ;2.1

25;Wonder Wings ;2.5

/* query 2 */

select id, name, distance2

from (

select *

from tbl1

where distance2 <= 2.0

order by distance2) a

union

select id, name, distance2

from (

select *

from tbl1

order by distance2

limit 5) b;

/* result 2 */

id;name;distance2

3;Earl of Sandwich ;0.1

4;Nails 'n More ;0.2

5;Mighty Medicine ;0.5

6;Jean Warehouse ;0.7

9;Ship Safe & Speedy ;0.9

2;Bagel Bonus ;1.2

22;City Hotel ;1.7

这个查询的性能和它一样好.第一个UNION部分选出了<2km.这是必要的,因为你想要所有的比赛.下一部分选择前5名并假设你有一个索引,这是很容易收集的.两个部分的组合(UNION)非常快.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值