简体   繁体   English

从数据库Codeigniter中加入的表格中选择一个列

[英]selecting a colum from joined tabels in database Codeigniter

I am trying to select column name level_name from table levels , which contains level_id and level_name , for a user to know what is their level, 我正在尝试从表levels选择列名称level_name ,其中包含level_idlevel_name ,以便用户知道其级别,

The table of users named as users and contain a level_id and user_id , but I get this error -> 用户表被命名为users并且包含一个level_iduser_id ,但是出现此错误->

Column 'level_id' in on clause is ambiguous on子句中的列“ level_id”不明确

SELECT `level_name` 
 FROM `levels` 
   JOIN `users` ON `level_id` = `level_id` WHERE `user_id` = '9'

here it is the code in the model 这是模型中的代码

public function level_ownprofile($user_id)
{
    $this->db->select('level_name');
    $this->db->from('levels');
    $this->db->join('users', 'level_id = level_id');
    $this->db->where('user_id', $user_id);
    $query = $this->db->get();
    return  $query;
}

thanks in advance :) 提前致谢 :)

Select l.level_name 
FROM levels l
JOIN users u
ON u.level_id = l.level_id 
and u.user_id = '9'


public function level_ownprofile($user_id)
{
$this->db->select('level_name');
$this->db->from('levels');
$this->db->join('users', 'levels.level_id = users.level_id');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return  $query;
}

Change the query to 将查询更改为

SELECT `level_name` 
 FROM `levels` l
   JOIN `users` u ON `u`.`level_id` = `l`.`level_id` 
 WHERE `user_id` = '9'

if you like the table name aliasing method, it is shorter and easier to read. 如果您喜欢表名别名方法,则它更短且更易于阅读。

Or 要么

SELECT `level_name` 
 FROM `levels` 
   JOIN `users` ON `users`.`level_id` = `levels`.`level_id` 
WHERE `user_id` = '9'

If you prefere to use the full table name everywhere. 如果您希望在任何地方都使用完整的表名。

Because both tables contain a column with the name level_id the query analyser need to know which one you are addressing. 因为两个表都包含一个名称为level_id的列,所以查询分析器需要知道您要寻址的是哪一个。

In codeigniter try 在codeigniter中尝试

public function level_ownprofile($user_id)
{
    $this->db->select('level_name');
    $this->db->from('levels l');
    $this->db->join('users u', 'u.level_id = l.level_id');
    $this->db->where('user_id', $user_id);
    $query = $this->db->get();
    return  $query;
}
public function level_ownprofile($user_id)
{
    $this->db->select('l.level_name');
    $this->db->from('levels as l');
    $this->db->join('users as u', 'l.level_id = u.level_id');
    $this->db->where('l.user_id', $user_id);
    $query = $this->db->get();
    return $query->results();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM