我是个 新手 我现在有30张表(没办法 就是需要这么多表 不能整合) 表的结构都是一样的 我现在要根据一定的条件然后读取出30条记录 并且按照日期把查询出来的结果进行排序 我现在用的查询语句类似
select * from (select a,b,c,date1 from biao1 where a="已售" order by date1)as t1
union all
select * from (select a,b,c,date1 from biao2 where a="已售" order by date1)as t1
union all
select * from (select a,b,c,date1 from biao3 where a="已售" order by date1)as t1
union all
select a,b,c,date1 from biao4 where a="已售" order by date1
然后 一直到 第30个表 我想问下 有哪位高手有方式优化下我的语句 或者有别的方法啊 特急 感激不尽啊。
select * from (select a,b,c,date1 from biao1 where a="已售" and b="轿车" order by date1 limit 30)as t1
union all
select * from (select a,b,c,date1 from biao2 where a="已售" and b="轿车" order by date1 limit 30)as t1
union all
select * from (select a,b,c,date1 from biao3 where a="已售" and b="轿车" order by date1 limit 30)as t1
union all
select a,b,c,date1 from biao4 where a="已售" and b="轿车" order by date1 limit 30
刚刚的语句有点错误 大概 就是这样的。就是 不知道 这个怎么去优化 数据库或者代码或者其他什么的 就是优化下查询 速度啦 。。。因为我现在的话这样查询的话 会很慢 我建立了一个 (b,date1)的索引 可是还是很慢的感觉
mysql 多表查询优化
答案:3 悬赏:40 手机版
解决时间 2021-03-06 08:01
- 提问者网友:轻浮
- 2021-03-05 09:18
最佳答案
- 五星知识达人网友:长青诗
- 2021-03-05 10:56
优化语句很简单:自定义函数帮您忙
先自定义一个函数,执行一次:
create function fun_tb(@fClass varchar(50))
return @Mytable table
(
a varchar(50) ,
b char(30),
c varcher(20)
)
as
begin
insert into @Mytable
select * from (select a,b,c,date1 from biao1 where a=@fClass order by date1 limit 30)as t1
union all
select * from (select a,b,c,date1 from biao2 where a=@fClass order by date1 limit 30)as t1
union all
select * from (select a,b,c,date1 from biao3 where a=@fClass order by date1 limit 30)as t1
union all.....................
return
end
上面..............是省略你的30表的语句,你不能省
以后在程序中调用时,只要写:
select * from dbo.Mytable('已售')
就行了
先自定义一个函数,执行一次:
create function fun_tb(@fClass varchar(50))
return @Mytable table
(
a varchar(50) ,
b char(30),
c varcher(20)
)
as
begin
insert into @Mytable
select * from (select a,b,c,date1 from biao1 where a=@fClass order by date1 limit 30)as t1
union all
select * from (select a,b,c,date1 from biao2 where a=@fClass order by date1 limit 30)as t1
union all
select * from (select a,b,c,date1 from biao3 where a=@fClass order by date1 limit 30)as t1
union all.....................
return
end
上面..............是省略你的30表的语句,你不能省
以后在程序中调用时,只要写:
select * from dbo.Mytable('已售')
就行了
全部回答
- 1楼网友:舊物识亽
- 2021-03-05 12:10
没有办法,你可以尝试一下把每个语句的order by去掉,这样会加快速度的,你也可以把这些语句做到一个视图里,这样方便些,但你这个语句已经没法改的更简洁了,好运
- 2楼网友:思契十里
- 2021-03-05 11:46
两个表中id相同,username和adduser是相同的。对吧? select tablea.* from tablea left join on tablea.id=tableb.tableaid where tablea.type=1 and tableb.username='admin' ===== left join是左联 from aaa,aaa这表是主表 left join bbb on ccc bbb这表是副表, ccc是条件,一定要两个表中都存在同样的数据才可进行这样的联结 ===== 查询字段在两个表都有数据,则都显示 主表有数据,副表没有,副表字段为空的值显示为null 主表没有数据,就不会显示。
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯