我的数据库中有 3 个表,其中Matches
表中的 team1
和 team2
id 等于TeamNames
表中的 team_id
。
表中的group
也等于Matches
GroupNames
表中的group_id
Matches
表
-----------------------------------
| team1 | team2 | group | count |
| 3 | 5 | 1 | 1 |
| 1 | 2 | 3 | 0 |
-----------------------------------
GroupNames
表
-----------------------
| group_id | name |
| 1 | Finals |
| 3 | Semi-Final |
-----------------------
TeamName
表
-----------------------
| team_id | name |
| 5 | Flowers |
| 2 | Rainbow |
-----------------------
我需要得到的是:
SELECT team1 , team1_name , team2 , team2_name , group , group_name WHERE count=1
我尝试连接表,但由于 team1 和 team2 中的每个都应该与 TeamName 表中的唯一 id 相关,我失败了,获取组名很容易,但我无法在单个查询中获取上述所有内容
问题:
这在单个查询中可能吗?
这可以使用CodeIgniter的"Active Record Class"来完成吗?
问题 1 的答案:是
问题2的答案:是
希望这对您有所帮助
$this->db->from('Matches m');
$this->db->select('m.team1,m.team2,m.group,m.count,tn1.name team1_name,tn2.name team2_name,gn.name group_name');
$this->db->join('TeamName tn1','tn1.team_id = m.team1');
$this->db->join('TeamName tn2','tn2.team_id = m.team2');
$this->db->join('GroupNames gn','gn.group_id = m.group');
$this->db->where('m.count',1);
$results=$this->db->get()->result();
是的。 与内部连接。
这是一个组合三个表的示例,如果需要,可以组合更多。
SELECT * FROM matches ma INNER JOIN groups gr ON ma.groupid = gr.groupid INNER JOIN teams te ON ma.teamid = te.teamid WHERE ma.count = 1
祝你好运!马丁