duandai0373 2018-06-10 16:26
浏览 105
已采纳

Mysql php:如何连续多次加入同一个表?

  • Team table has:

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

      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)?

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;
}
  • 写回答

1条回答 默认 最新

  • duanbi1983 2018-06-10 16:43
    关注

    It's best to answer this as purely an SQL question, which it is. 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)

    A common thing is to number the tables as t1, t2, t3, etc.

    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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵