Codeigniter加入表?

时间:2013-01-08 12:43:52

标签: php mysql codeigniter

我有这种表结构:

Table Name: collisions
Fields: id, creator1, creator2
(1, 1, 2) - simple data in my sql table

Table Name: creators
Fields: id, artistname
(1, john smith)- simple data in my sql table
(2, steven michael)- simple data in my sql table

我需要的是加入这些表格,这样我就可以获得艺术家名称而不是creator1 id和creator 2 id。

这是我到目前为止所做的:

$this->db->select('collisions.*, creators.artist_name AS cr1, creators.artist_name as cr2');
$this->db->join('creators', 'collisions.creator1 = cr1.id AND collisions.creator2 = cr2.id', 'left');
$data = $this->db->get('collisions')->result();

但是我收到了这个错误:

Unknown column 'cr1.id' in 'on clause'

SELECT `collisions`.*, `creators`.`artist_name` AS cr1, `creators`.`artist_name` as cr2 FROM (`collisions`) LEFT JOIN `creators` ON `collisions`.`creator1` = `cr1`.`id` AND collisions.creator2 = cr2.id

有人能告诉我我做错了吗?

2 个答案:

答案 0 :(得分:0)

请使用实际的表名而不是别名:

$this->db->select('collisions.*, creators.artist_name AS cr1, creators.artist_name as cr2');
$this->db->join('creators', 'collisions.creator1 = creators.id AND collisions.creator2 = creators.id', 'left');
$data = $this->db->get('collisions')->result();

你不能使用别名的原因是sql的执行顺序如下:

1)FROM clause
2)WHERE clause
3)GROUP BY clause
4)HAVING clause
5)SELECT clause
6)ORDER BY clause 

因为您使用的是在选择子句中创建的别名,该子句在 where 子句之后执行。

这就是为什么你不能使用不存在的别名。

答案 1 :(得分:0)

这完成了工作

    $this->db->select('collisions.*, cr1.artist_name as cr1, cr2.artist_name as cr2');
    $this->db->join('creators AS cr1', 'collisions.creator1 = cr1.id', 'left');
    $this->db->join('creators AS cr2', 'collisions.creator2 = cr2.id', 'left');
    $data = $this->db->get('collisions')->result();