2016-04-29 5 views
0

私の問題では、私は旅行ルートテーブルと都市テーブルを持っています。ルートテーブルはあなたの起源都市とあなたの目的地の都市を都市ID、名前は別の表にあります。SQLクエリが間違っていると、1つのテーブルから2つの名前を検索する必要があります

私はX市から始まるすべてのルートを検索したい、このために、私はこのクエリ

SELECT ciudad.nombre as Origen, 
ciudad.nombre as Destino, 
km as Distancia, 
rutas.km*rutas.precio_km as Precio, 
fecha as Fecha 
FROM rutas, ciudad where "Santiago"=ciudad.nombre and ciudad.id_ciudad=rutas.ciudad_or; 

enter image description here

を作った。これは私が得る結果であり、注意原産地= DESTINO

enter image description here

これはRoutesテーブルです.ciudad_orとciudad_deはfromとtoの都市です。

enter image description here

これは私の都市テーブル

ですが、それもある(私はそれが正しい宛先を表示させる方法がわからない、私の元と私の目的地に同じ都市を印刷します同上)

私は都市名でルートを検索してい

+0

いくつかのサンプルデータをお送りください。 – Blank

+0

いくつかの画像を追加しました – user3577419

+0

画像ではありません。テストテーブルを作成するためにコピーして貼り付けることはできません。表を作成するDDLと、表を作成するDML –

答えて

1

あなたは...それぞれのための二重加入あなたの都市にテーブルを行う必要があり

SELECT 
     r.id_ruta, 
     r.cuidad_or, 
     Orig.nombre as Origen, 
     r.cuidad_de, 
     Dest.nombre as Destino, 
     any_other_columns... 
    from 
     Routes r 
     join ciudad as Orig 
      ON r.ciudad_or = Orig.id_ciudad 
     join ciudad as Dest 
      ON r.cuidad_de = Dest.id_ciudad 
    where 
      orig.nombre="Santiago" 
     OR dest.nombre="Santiago" 

は今、より良いアプローチをしているOR発信または着信先を探している私はあなたのシウダッドテーブル上の2つのインデックスを示唆している

のような事前予選何かのUNION経由になります。 cuidad_de

SELECT 
     r.id_ruta, 
     r.cuidad_or, 
     Orig.nombre as Origen, 
     r.cuidad_de, 
     Dest.nombre as Destino, 
     any_other_columns... 
    from 
     Routes r 
     join ciudad as Orig 
      ON r.ciudad_or = Orig.id_ciudad 
     join ciudad as Dest 
      ON r.cuidad_de = Dest.id_ciudad 
    where 
     orig.nombre="Santiago" 
UNION 
SELECT 
     r.id_ruta, 
     r.cuidad_or, 
     Orig.nombre as Origen, 
     r.cuidad_de, 
     Dest.nombre as Destino, 
     any_other_columns... 
    from 
     Routes r 
     join ciudad as Orig 
      ON r.ciudad_or = Orig.id_ciudad 
     join ciudad as Dest 
      ON r.cuidad_de = Dest.id_ciudad 
    where 
     dest.nombre="Santiago" 

上cuidad_orの一つ、別の組合が一つに両方を組み合わせしようとするよりも、個々のインデックスに良く動作します。うわー...間違った列の名前、ピリオド、スペーシングで今夜指で悪い...遅くなってしまった。

関連する問題