codeigniter活动记录左连接 [英] codeigniter active record left join

查看:147
本文介绍了codeigniter活动记录左连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个mysql表。

I have 3 mysql tables.

Table 1 user  
id | name  

Table 2 emails  
id | email  

Table 3 user_email  
user_id | email_id  

我没有查询多表的经验。

使用codeigniter活动记录,我想找出基于用户id的用户电子邮件地址,pls建议如果下面的代码是正确的?

I have no experience in query multi tables.
Using codeigniter active record, i want to find out the user email address based on the user id, pls advise if the below code is correct ?

$CI->db->select('email');
$CI->db->from('emails');
$CI->db->where('id', $userid);
$CI->db->join('user_email', 'user_email.user_id = emails.id', 'left');
$query = $CI->db->get();  


推荐答案

您的表格,您正在比较电子邮件的ID与提供的 $ user_id

You have wrong where clause you need to compare user_id from your table ,you are comparing the id of email to the provided $user_id

$CI->db->select('email');
$CI->db->from('emails');
$CI->db->where('user_id', $userid);
$CI->db->join('user_email', 'user_email.user_id = emails.id', 'left');
$query = $CI->db->get(); 

一个更有用的方法是为表赋予别名,因此具有相同列的表不会有混淆

A more useful way is to give aliases to your tables so the tables with same columns will not have any confusion

$CI->db->select('e.email');
$CI->db->from('emails e');
$CI->db->join('user_email ue', 'ue.user_id = e.id', 'left');
$CI->db->where('ue.user_id', $userid);
$query = $CI->db->get(); 

这篇关于codeigniter活动记录左连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆