【问题标题】:How to join tow times the same table?如何加入两次同一张表?
【发布时间】:2019-10-01 01:13:28
【问题描述】:

我需要加入两次同一张表,如何在 Codeigniter 中完成?

表匹配


  • match_id
  • team_home_id
  • team_away_id
  • score_home
  • score_away
  • group_id
  • round_id
  • 获胜者
  • 开始日期
  • 开始时间

表团队


  • team_id
  • 姓名
  • 代码

这是我必须加入的两张表。桌队必须参加两次桌队比赛。

$this->db->select('*')
         ->from('match, team')
         ->join('team AS team_a', 'match.team_home_id = team_a.team_id')
         ->join('team AS team_b', 'match.team_away_id = team_b.team_id')
         ->get()->result();

我的结果是比赛,只是其中一支球队:/

【问题讨论】:

  • 一个很好的提示是永远不要使用邪恶的SELECT *。相反,总是命名(并限定)您实际想要返回的列。
  • 谢谢草莓,是的,这是一个很棒的提示,通常我只会从表格中选择我需要的东西。您是否有机会在这里尝试解决我的问题?
  • 差不多,如果你按照上面的建议,任何剩余的问题都会消失。
  • 不幸的是并没有消失,我将选择更改为:matches.score_home、matches.score_away、matches.winner、matches.start_date、matches.start_time、team_a.name、team_a.code、team_b。名称,team_b.code。结果只是 match 和 team_b。如果我删除 team_b 加入我会得到 team_a。

标签: mysql codeigniter


【解决方案1】:

谢谢你,草莓的帮助。

在我的查询中,我总是得到最后一个加入的团队,因为看起来 Codeigniter 覆盖了具有相同名称的列,team_a.name 和 team_a.code 在最终的 result_array() 中表示为数组键“名称”和“代码”与 team_b.name 和 team_b.code 相同。

所以我需要为列添加别名的不仅仅是表的别名:

    $this->db->select('tips.stake, tips.odd, 
    matches.score_home, matches.score_away, matches.winner, matches.start_date, matches.start_time,
    team_home.name AS team_home_name, team_home.code AS team_home_code, team_away.name AS team_away_name, team_away.code AS team_away_code');

    $this->db->from('tips');
    $this->db->join('matches', 'matches.match_id = tips.match_id');
    $this->db->join('`teams` `team_home`', 'team_home.team_id = matches.team_home_id');
    $this->db->join('`teams` `team_away`', 'team_away.team_id = matches.team_away_id');

    $query = $this->db->get();

【讨论】:

    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 2010-09-17
    • 2014-09-15
    相关资源
    最近更新 更多