[英]How to join two tables with multiple IDs from one table used in other table?
I need to join two tables tableA
and tableB
, but the problem is that in tableB
I have two IDs from tableA
and I need to join them so I get both values. 我需要tableA
两个表tableA
和tableB
,但是问题是在tableB
我有来自tableA
两个ID ,因此我需要将它们tableA
起来,以便同时获得两个值。 I would like to achieve it using Codeigniter's active record class. 我想使用Codeigniter的活动记录类来实现它。 Here is a small demo: 这是一个小演示:
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 doesn't work: 这不起作用:
$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();
The final result needs to be something like this: 最终结果需要是这样的:
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
)
)
You mix up tableA and tableB in your query. 您在查询中混合了tableA和tableB。 For each item in B you want something, so start joining there. 对于B中的每个项目,您都想要一些东西,所以从那里开始加入。 Then, join renamed table, and select the items from the renamed tables. 然后,加入重命名的表,并从重命名的表中选择项目。
->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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.