2017-04-10 14 views
0

私は単純なバスチケット予約システムを構築しています。私はMySQLデータベースに2つのテーブルを持っています。 destinationsおよびlines。これは、その構造です:MySQLは2つのテーブルを選択して、最初のテーブルのフィールドの値を2番目のテーブルのフィールドの値に置き換えます。

ので
+------------------+ +---------------------------------------------------+ 
| destinations | |      lines      | 
+--+---------------+ +--+-----------+---------+-------------+------------+ 
|id|  name  | |id| dest_from | dest_to | depart_time | drive_time | 
+--+---------------+ +--+-----------+---------+-------------+------------+ 
|1 | Boston  | |1 |  1  | 2 | 08:00 | 06:00:00 | 
|2 | New York City | |2 |  1  | 3 | 08:00 | 04:00:00 | 
|3 | Chicago  | |3 |  1  | 4 | 08:00 | 04:00:00 | 
|4 | Miami   | |4 |  2  | 1 | 13:00 | 06:00:00 | 
+--+---------------+ |5 |  2  | 3 | 13:00 | 06:00:00 | 
         |6 |  2  | 4 | 13:00 | 04:00:00 | 
         |7 |  3  | 1 | 11:00 | 04:00:00 | 
         |8 |  3  | 2 | 11:00 | 06:00:00 | 
         |9 |  3  | 4 | 11:00 | 06:00:00 | 
         |10|  4  | 1 | 09:00 | 04:00:00 | 
         |11|  4  | 2 | 09:00 | 04:00:00 | 
         |12|  4  | 3 | 09:00 | 06:00:00 | 
         +--+-----------+---------+-------------+------------+ 

、あなたが見ることができるように、私はdest_fromdest_tolines表に書かれた、destinationsのIDを使用します。

アプリケーションのインタフェースは、ユーザが、アプリケーションがdest_fromdest_toが宛先に等しくSELECT * FROM linesに、ユーザによって選択した「検索」をクリックした後、出発点と到着点を選択することを可能にします。

私の質問は:単一のSQLクエリで両方のテーブルを選択して "タイアップ"する方法です。Line number 1, from Boston to New York City, departs at 08:00 from Boston and will be in New York City at 14:00.(08:00 + 06:00時間= 14:00)のようなものが得られます。

JOINを使用する必要があります。その場合は、どのようにクエリを表示する必要がありますか?

ありがとうございます!

+2

はい(未テストの擬似SQL、それはあなたのアイデアを与える必要があります)。 'JOIN'を2回使用します。 –

+0

OKですが、 'destination'テーブルの1つのフィールドに依存して、' lines'テーブルに2つのフィールドがあるので、クエリはどのようになりますか? –

+0

@EmilAvramovはい、あなたは 'JOIN'を使う必要があります。 – user3441151

答えて

1

は、次の2つが、内側にすることができますが、2を実行する必要があり

select d1.name as from_city, d2.name as to_city from lines 
inner join destinations d1 on d1.id = lines.dest_from 
inner join destinations d2 on d2.id = lines.dest_to 
+0

はい、私の答えを更新しました –

0

参加し、それぞれのフィールド上のいずれかのように同じテーブルの宛先と合流します。 this'ishのように:

SELECT from.name AS 'from' , to.name AS 'to', depart_time, drive_time 
LEFT INNER JOIN destinations to ON dest.id = dest_to 
LEFT INNER JOIN destinations from ON dest.id = dest_from 

+0

注:*宛先*時刻*を取得するには、あなたのクエリに日付型の関数を使用することができますが、他の場所 – Svish

関連する問題