MySQL将不同列上同一行中的两个表连接起来

时间:2012-11-15 08:33:01

标签: mysql inner-join between

我要加入两个目的地相同但原点值不同的表。我确信我不善言辞。但希望你能通过我的代码得到我想要的东西:

的MySQL

SELECT 
option_places_db.plc_en AS from_en, 
option_places_db.plc_th AS to_en, 
concat( time_start_hr, ':', time_start_min ) AS time1, 
concat( time_end_hr, ':', time_end_min ) AS time2, 
price_adult, 
price_child
FROM `time_table_boat`
INNER JOIN option_places_db ON time_table_boat.org = option_places_db.plc_id
ORDER BY time_table_boat.org ASC

time_table_boat enter image description here

option_places_db

enter image description here

根据time_table_boat表。我期待:

from_en    to_en     time1    time2    price_adult    price_child
Aonang     Phi Phi   09:00    11:00    450            350
Phi Phi    Aonang    15:30    17:00    450            350

但是从运行mySQL开始,它变成了这样: enter image description here

列'to_en'与time_table_boat.des = option_places_db(= 3)不匹配。我试图添加更多的内部联接行,但它会出现相同目标表名称的错误。

2 个答案:

答案 0 :(得分:3)

试试这个

SELECT 
    org_places.plc_en AS from_en, 
    des_places.plc_en AS to_en, 
    CONCAT( time_start_hr, ':', time_start_min ) AS time1, 
    CONCAT( time_end_hr, ':', time_end_min ) AS time2, 
    price_adult, 
    price_child
FROM `time_table_boat`
INNER JOIN 
    option_places_db AS org_places ON time_table_boat.org = org_places.plc_id
INNER JOIN 
    option_places_db AS des_places ON time_table_boat.des = des_places.plc_id
ORDER BY time_table_boat.org ASC

答案 1 :(得分:1)

试试这个:

SELECT
placeOrg.plc_en AS from_en, 
placeDes.plc_th AS to_en, 
concat( time_start_hr, ':', time_start_min ) AS time1, 
concat( time_end_hr, ':', time_end_min ) AS time2, 
price_adult, 
price_child
FROM `time_table_boat`
INNER JOIN option_places_db AS placeOrg ON time_table_boat.org = placeOrg.plc_id
INNER JOIN option_places_db AS placeDes ON time_table_boat.des= placeDes.plc_id
ORDER BY time_table_boat.org ASC

您需要表option_places_db中的两个不同的名称,因此您需要将其加入两次。第一次检索原始名称,第二次检索目标名称。 您可以看到您使用相同的表格来源和目的地,您只需将它们链接两次,并给它一个临时名称,以区分您得到的响应。

编辑:更正了查询