简体   繁体   中英

How do I reference table dot column notation in a MySQL query

SELECT * from meets
 LEFT JOIN teams as hteam on meets.meet_hometeam=hteam.team_id 
 LEFT JOIN teams as ateam on meets.meet_awayteam=ateam.team_id 
 LEFT JOIN teams as altloc on (meets.meet_altloc=altloc.team_id and meets.meet_altloc!='')
 where meet_date between ($now+(4*86400)) and ($now+(5*86400) or meets.meet_id='2')

In PHP:

$var = $queryvar->fetch_object();

I'm having issues when I call $var->ateam.team_town it is just treating the dot as concatenation and not as an object to the table.

Don't SELECT * when doing JOIN or UNION queries. Instead, be specific about the columns you need, and if columns have the same name in different tables, you need to assign aliases to them.

Aside from the necessity of differentiating columns with similar names, you get the benefit of being deterministic about the order in which they're returned and protection from future schema changes that add columns you don't want from being automatically pulled into this (like image blob data or something).

SELECT
  /* specify columns from each table with aliases */
  hteam.team_id AS hometeam_id,
  ateam.team_id AS awayteam_id,
  hteam.team_town AS hometeam_town,
  ateam.team_town AS awayteam_town,
  ...
  ...
  etc...
FROM meets
 LEFT JOIN teams as hteam on meets.meet_hometeam=hteam.team_id 
 LEFT JOIN teams as ateam on meets.meet_awayteam=ateam.team_id 
 LEFT JOIN teams as altloc on (meets.meet_altloc=altloc.team_id and meets.meet_altloc!='')
 WHERE meet_date between ($now+(4*86400)) and ($now+(5*86400) or meets.meet_id='2')

Then in your PHP, just call it by the alias you chose: $var->hometeam_town, $var->hometown_id, $var->awayteam_town etc...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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