java mysql联合索引是怎么存的

java mysql联合索引是怎么存的,第1张

联合索引是由多个字段组成的索引。CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name[USING index_type]ON tbl_name (index_col_name,...)index_col_name:col_name[(length)] [ASC | DESC]如果你经常要用到多个字段的多条件查询,

其实我也没有啥好办法,我甚至推荐你使用楼上说的方法,直接select * 将数据全部查出后,在service中用java处理数据更加方便。

如果要强行使用sql查出来,我这里写了这么一段:

首先因为是同一张表,根据不同条件将结果拼接在一起,我能想到的就是用left join,我按照不同条件将数据分成如下几段:

a段:姓名段,作为left join的主表,只有姓名;

b段:吃了早餐段;

c段:没吃早餐段;

d段:吃了晚餐段;

e段:没吃晚餐段;

f段:吃了饭段;

g段:没吃饭段。

除了a段以外,其他段都是根据自身条件

SELECT

name,

count(*)    count,

sum(weight) sum,

然后依次左连接将所有段通过姓名连接到一起,最终组成的sql语句如下:

SELECT

a.name 姓名,

ifnull(b.count, 0) 吃了早餐的次数,

ifnull(b.sum, 0)   吃了早餐的重量,

ifnull(c.count, 0) 没吃早餐的次数,

ifnull(c.sum, 0)   没吃早餐的重量,

ifnull(d.count, 0) 吃了晚餐的次数,

ifnull(d.sum, 0)   吃了晚餐的重量,

ifnull(e.count, 0) 没吃晚餐的次数,

ifnull(e.sum, 0)   没吃晚餐的重量,

ifnull(f.count, 0) 吃了饭的次数,

ifnull(f.sum, 0)   吃了饭的重量,

ifnull(g.count, 0) 没吃饭的次数,

ifnull(g.sum, 0)   没吃饭的重量

FROM

(SELECT DISTINCT name

FROM T) a LEFT JOIN

(SELECT

name,

count(*)    count,

sum(weight) sum

FROM T

WHERE type = 0 AND status = 0

GROUP BY name) b ON a.name = b.name

LEFT JOIN

(SELECT

name,

count(*)    count,

sum(weight) sum

FROM T

WHERE type = 0 AND status = 1

GROUP BY name) c ON a.name = c.name

LEFT JOIN

(SELECT

name,

count(*)    count,

sum(weight) sum

FROM T

WHERE type = 1 AND status = 0

GROUP BY name) d ON a.name = d.name

LEFT JOIN

(SELECT

name,

count(*)    count,

sum(weight) sum

FROM T

WHERE type = 1 AND status = 1

GROUP BY name) e ON a.name = e.name

LEFT JOIN

(SELECT

name,

count(*)    count,

sum(weight) sum

FROM T

WHERE status = 0

GROUP BY name) f ON a.name = f.name

LEFT JOIN

(SELECT

name,

count(*)    count,

sum(weight) sum

FROM T

WHERE status = 1

GROUP BY name) g ON a.name = g.name

T表结构为:

(因为以name字段进行连接,type和status作为条件,建议以该三个字段作为索引)

T表测试数据为:

运行结果为:


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/7313214.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-04
下一篇 2023-04-04

发表评论

登录后才能评论

评论列表(0条)

保存