1

我有这种表结构:

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

有人可以告诉我我做错了什么吗?

4

2 回答 2

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 

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

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

于 2013-01-08T12:50:07.780 回答
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();
于 2013-01-08T15:09:13.823 回答