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  

解决方案 »

  1.   

    select a.cityname,c.cityname,b.arrivedate,b.status from table1 a,table2 b, table1 c where a.citycode=b.f_city and c.citycode=b.t_city
      

  2.   

    select (select cityname from table1 where f_city = citycode),
    (select cityname from table1 where t_city = citycode),arrivedate,status
    from table2;樓上的SQL速度較慢,笛卡兒乘積太大.
      

  3.   

    我觉得做一个新表最简单create table table3 as (select * from table2)update table3 set f_city=table1.cityname where f_city=table1.citycodeupdate table3 set t_city=table1.cityname where t_city=table1.citycodeselect * from table3
      

  4.   

    或者用join
    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不过没有验证这种语法对不对
      

  5.   

    我也遇到过这样的问题...
    当时是建立一个视图view1:
    select * from table1
    然后写SQL
      

  6.   

    zhuzhichao(竹之草)的最好,我试过了....... 
      

  7.   

    学习,学习
    zhuzhichao(竹之草)功力很好呀,不过我有一个问题:
    我分析了你和playyuer(女㊣爱),karma(无为)得语句,表面上是不一样,但是重原理
    上执行是一样的,可能是我的水平不够,希望能指教一下你的语句和前两位的笛卡兒乘積
    差别在哪?  
      

  8.   

    to crycoming(瞎编):
    表面上不一樣,實質上原理也不一樣!假設有兩表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中有多少紀錄,結果積就只有多少條紀錄.如果兩個表數據只有一條兩條,那麼看不出效果.
    如果兩個表數據都有成千上萬條或是百萬條的話.
    嘿嘿,這個差距就大了.說了這麼多,希望你能明白.我是數據庫開發版斑竹,希望你能常來數據庫版.
    :)
      

  9.   

    抱歉,上面的有筆誤.
    將table3換成table2.
      

  10.   

    谢谢zhuzhichao(竹之草)
    我以后会常去 數據庫開發版
      

  11.   

    to zhuzhichao(竹之草):
       非相关子查询是快!
       你这是相关子查询,应该不会快!
      

  12.   

    to playyuer(女㊣爱):
    你可以哢一些數據測試一下.
      

  13.   

    这个工作可以放在前台进行,把代码表利用recordset缓冲在本地,
    然后展现的时候,再作相应的替换
      

  14.   

    其实这个问题很常见!
    即:
    一个主表的不同字段共享同一码表(不同字段的值域来自同一张表)!
    最简单的解决办法就是起别名!to zhuzhichao(竹之草):
       首先你肯定是相关子查询!不一定所有数据库都支持你这种写法!所有的查询都是笛卡儿积的子集!等值连接还是很快的!
      

  15.   

    其实就是把 Table1 看成两个表!
      

  16.   

    谢谢大家的帮助和关心。SQL语句的效率问题确实是非常重要的一个因素,希望以后能多多得到大家的指教!本想给大家多加点分的,谁知最多只能给到38分,抱歉。