SELECT T1.cityname,T2.cityname,table2.arrivedate,table2.status
FROM table2,Table1 AS T1,Table1 AS T2
WHERE table2.f_city = T1.citycode AND table2.t_city = T2.citycode
FROM table2,Table1 AS T1,Table1 AS T2
WHERE table2.f_city = T1.citycode AND table2.t_city = T2.citycode
(select cityname from table1 where t_city = citycode),arrivedate,status
from table2;樓上的SQL速度較慢,笛卡兒乘積太大.
select * from table1 inner join
(select * from table1 inner join table2 on table1.citycode=table2.f_city) as table3
on table1.citycode=table3.t_city不过没有验证这种语法对不对
当时是建立一个视图view1:
select * from table1
然后写SQL
zhuzhichao(竹之草)功力很好呀,不过我有一个问题:
我分析了你和playyuer(女㊣爱),karma(无为)得语句,表面上是不一样,但是重原理
上执行是一样的,可能是我的水平不够,希望能指教一下你的语句和前两位的笛卡兒乘積
差别在哪?
表面上不一樣,實質上原理也不一樣!假設有兩表table1,table2
table1有1000條紀錄,table2有100條紀錄.如果這樣:
select * from
table1 a,table2 b,table3 c;--那麼將得到1000*100*100 = 10000000條紀錄
這個紀錄數就是我們常說的笛卡兒乘積數.就算:
select * from
table1 a,table2 b,table3 c
where ...;--後面加了where條件,也是從這個笛卡兒乘積中篩選數據.但是這樣就不一樣了:
select table1.a1,
(select b2 from table2 where table1.a2 = table2.b1),
(select b3 from table2 where table1.a3 = table2.b1)
from table1;
--可以將(select b2 from table2 where table1.a2 = table2.b1)
這樣的子查詢看做常數.
其實就相當與:
select table1.a1,'某某','某某某' from talbe1;
table1中有多少紀錄,結果積就只有多少條紀錄.如果兩個表數據只有一條兩條,那麼看不出效果.
如果兩個表數據都有成千上萬條或是百萬條的話.
嘿嘿,這個差距就大了.說了這麼多,希望你能明白.我是數據庫開發版斑竹,希望你能常來數據庫版.
:)
將table3換成table2.
我以后会常去 數據庫開發版
非相关子查询是快!
你这是相关子查询,应该不会快!
你可以哢一些數據測試一下.
然后展现的时候,再作相应的替换
即:
一个主表的不同字段共享同一码表(不同字段的值域来自同一张表)!
最简单的解决办法就是起别名!to zhuzhichao(竹之草):
首先你肯定是相关子查询!不一定所有数据库都支持你这种写法!所有的查询都是笛卡儿积的子集!等值连接还是很快的!