将表连接成4个列

时间:2017-06-05 03:53:39

标签: mysql codeigniter join

我在显示来自不同表的4个不同的列时遇到问题,有关更多详细信息,请参阅下面的内容:

表格个人(tbl_personal)

+---+-----+------------+
|ID |Name |Skill       |
+---+-----+------------+
| 1 | Nia | Accountant |
| 2 | Tia | Banking    |
| 3 | Ria | Technicall |
| 4 | Dia | Admin      |
+---+-----+------------+

表大师(tbl_master)

+---+---------+---------+
|ID |Employee1|Employee2|
+---+---------+---------+
| 1 | 1       | 2       |
| 2 | 2       | 1       |
| 3 | 3       | 4       |
+---+---------+---------+

我想在codeigniter中显示上面的tbl_master网页,如下所示:

+---+-------+-----------+-------+-----------+
|ID |Name 1 |Skill 1    |Name 2 |Skill 2    |
+---+-------+-----------+-------+-----------+
| 1 | Nia   | Accountant| Tia   | Banking   |
| 2 | Tia   | Banking   | Nia   | Accountant|
| 3 | Ria   | Technicall| Dia   | Admin     |
+---+---------+---------+-------+-----------+

如果有任何关于我从tbl_personal加入tbl_master的建议请咨询, 感谢您的支持......

2 个答案:

答案 0 :(得分:1)

你需要加入两次私人表。如下所示

select tp1.name name1,tp1.skill skill1,tp2.name name2,tp2.skill skill2 
from tbl_master tm
join tbl_personal tp1
on tm.Employee1 =tp1.ID
join tbl_personal tp2
on tm.Employee2 =tp2.ID

答案 1 :(得分:0)

我认为你必须使用2个连接。加入

后,您还必须小心选择列
SELECT tp1.name as Name1, tp1.Skill as Skill1,tp2.name as Name2, tp2.Skill as Skill2
FROM tbl_master tm1
JOIN tbl_personal tp1 on tp1.id = tm1.Employee1
JOIN tbl_personal tp2 on tp2.id = tm1.Employee2

这应该是此查询的输出。

enter image description here

只需在选择查询中添加ID列。