我需要加入两个表tableA
和tableB
,但问题是在tableB
我有tableA
的两个 ID 和我需要加入他们,所以我得到了两个价值观。我想使用Codeigniter的活动记录类来实现它。这是一个小型演示:
tableA:
╔══════════╦════════════╗
║ video_id ║ video_name ║
╠══════════╬════════════╣
║ 1 ║ short ║
║ 2 ║ long ║
║ 3 ║ black ║
║ 4 ║ white ║
╚══════════╩════════════╝
tableB
╔═════════╦════════╦════════╗
║ pair_id ║ pair_a ║ pair_b ║
╠═════════╬════════╬════════╣
║ 1 ║ 1 ║ 2 ║
║ 2 ║ 1 ║ 4 ║
║ 3 ║ 4 ║ 3 ║
║ 4 ║ 3 ║ 2 ║
╚═════════╩════════╩════════╝
这不起作用:
$this->db->select('*')
->from("tableA")
->join('tableB AS A', 'tableA.video_id = A.pair_a')
->select("tableA.video_name as VIDEO_A")
->join('tableB AS B', 'tableA.video_id = B.pair_b')
->select("tableA.video_name as VIDEO_B")
->get()
->result();
最终结果必须是这样的:
stdClass Object
(
[0] => stdClass Object
(
[VIDEO_A] => short
[VIDEO_B] => long
)
[1] => stdClass Object
(
[VIDEO_A] => short
[VIDEO_B] => white
)
[2] => stdClass Object
(
[VIDEO_A] => white
[VIDEO_B] => black
)
[3] => stdClass Object
(
[VIDEO_A] => black
[VIDEO_B] => long
)
)
答案 0 :(得分:2)
您在查询中混合了tableA和tableB。对于B中的每个项目,你想要一些东西,所以开始加入那里。然后,加入重命名的表,并从重命名的表中选择项目。
->from("tableB")
->join('tableA AS pairA', 'pairA.video_id = tableB.pair_a')
->join('tableA AS pairB', 'pairB.video_id = tableB.pair_b')
->select("pairA.video_name as VIDEO_A, pairB.video_name as VIDEO_B")