简体   繁体   English

从同一个表联接

[英]Joins from same table

I am trying to join the same table "travel_plan" twice, as the value(s) I need are location_from & location_to in which I can then join the value to my cities table to grab the city name. 我尝试将同一张表“ travel_plan”连接两次,因为我需要的值是location_fromlocation_to ,然后可以在其中将值连接到我的citys表以获取城市名称。

SELECT * FROM travel_plan 
LEFT JOIN Cities ON Cities.CityID = travel_plan.location_to AS plan_to 
LEFT JOIN Cities ON Cities.CityID = travel_plan.location_from AS plan_from
LEFT JOIN user_table ON travel_plan.user_id = user_table.id 
ORDER BY date_from DESC LIMIT 0,4") or die(mysql_error());

You need to use table aliases correctly when you're joining the same table more than once, as you're doing with Cities in this query. 当您多次连接同一张表时,需要正确使用表别名,就像在此查询中使用Cities

     SELECT * 
       FROM travel_plan  AS tr
  LEFT JOIN Cities       AS C1     ON  C1.CityID = tr.location_to 
  LEFT JOIN Cities       AS C2     ON  C2.CityID = tr.location_from 
  LEFT JOIN user_table   AS us     ON tr.user_id = us.id 
   ORDER BY date_from DESC 
      LIMIT 0,4

The way you wrote your query, the LEFT JOIN AS clauses were misplaced and not used for qualifying the column names. 您编写查询的方式中,LEFT JOIN AS子句放错了位置,并且没有用于限定列名。

This use of SELECT * is really suboptimal, however. 但是,对SELECT *这种使用实际上不是最佳的。 From this four-table JOIN, SELECT * kicks back lots of columns with duplicate names, which fouls up _fetch_assoc() methods in php. 从这个四表的JOIN中, SELECT * _fetch_assoc()了很多具有重复名称的列,这使php中的_fetch_assoc()方法陷入_fetch_assoc()

Your best bet is to enumerate the columns you fetch, and provide aliases so they don't end up with the same names. 最好的选择是枚举您获取的列,并提供别名,以使它们不会以相同的名称结尾。 I don't know the names of your columns so I have to guess, but it would go something like this. 我不知道您的列的名称,所以我不得不猜测,但是这样的话。

SELECT us.name, us.id AS userid, 
       C1.cityname AS to_cityname,
       C2.cityname AS from_cityname,
  FROM ....

Then you'll find the values in $result['from_cityname'] after you fetch each row. 然后,在获取每一行后,您将在$ result ['from_cityname']中找到值。

You misuse the AS keyword, it can be only used in the select part of the query (before FROM), or optionally as alias for table references. 您滥用了AS关键字,它只能在查询的选择部分(在FROM之前)使用,也可以选择用作表引用的别名。 But not in the ON part of a join. 但不在联接的ON部分。 I guess what you want is: 我想你想要的是:

SELECT *, c1.City as toCity, c2.City as fromCity  FROM travel_plan LEFT JOIN Cities c1 ON c1.CityID = travel_plan.location_to LEFT JOIN Cities c2 ON c2.CityID = travel_plan.location_from LEFT JOIN user_table ON travel_plan.user_id = user_table.id ORDER BY date_from DESC LIMIT 0,4

Now you can access the the column aliases toCity and fromCity in your resultset, even though the the original column names are the same. 现在,您可以访问别名列toCityfromCity在你的结果集,即使原来的列名是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM