简体   繁体   English

Mysql PHP:如何多次连接同一张表?

[英]Mysql php: How to join same table multiple times?

  • Team table has: Team表具有:

      ID | TEAM --------+---------- 1 | A 2 | B 
  • Result table has: Result表具有:

      fk_ID1 | fk_ID2 | RESULT ----------+-----------+----------- 1 | 2 | 5:0 2 | 1 | 2:3 

How to Inner JOIN table, to get: (A 5:0 B) & (A 2:3 B) ? 如何在Inner JOIN表中获取: (A 5:0 B) & (A 2:3 B)

My code example: 我的代码示例:

public function getResultList($limit, $offset) {
    $query = "  SELECT result_id,
                       t1.name name1,
                       t2.name name2,
                       team1_goals,
                       team2_goals,
                       date
                FROM results
                    INNER JOIN team t1 ON fk_tm1_id=tm_id
                    INNER JOIN team t2 ON fk_tm2_id=tm_id";
            $data = mysql::select($query);
    return $data;
}

It's best to answer this as purely an SQL question, which it is. 最好仅作为一个SQL问题来回答这个问题。 You need to assign a table alias when joining the same table two or more times. 当连接同一张表两次或更多次时,您需要分配一个表别名。

You seem to only be assigning aliases to the column. 您似乎只为该列分配别名。 To assign an alias to a column or table, you can add the alias directly after the column or table name (AS can also be used but isn't necessary for MySQL) 要将别名分配给列或表,您可以在列或表名之后直接添加别名(也可以使用AS,但对于MySQL来说不是必需的)

A common thing is to number the tables as t1, t2, t3, etc. 常见的做法是将表编号为t1,t2,t3等。

SELECT t1.name name1, t2.name name2 FROM ...
INNER JOIN team_table t1 ON ...
INNER JOIN team_table t2 ON ...

This aliases the first join as t1 and the second join as t2, which you would use when accessing data from that specific join (SELECT t1.name). 这将第一个连接的别名命名为t1,将第二个连接的别名命名为t2,在从该特定连接(SELECT t1.name)访问数据时将使用它们。

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

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