我有这个查询在MySql 5上完美运行
'SELECT a.id, a.name, a.date, c.name FROM artist as a, country as c WHERE a.country_id=c.id'
基本上它从艺术家表中选择id,name和date,然后用国家表中的相应名称替换国家的id。
注意:artist.country_id是外键,即country.id。每个艺术家都属于某个国家,其表格中有country_id。我需要为艺术家获取数据,但也要用适当的名称替换country_id。我不想为国家显示号码,我想显示国家/地区的名称。
$artists = $this->db->query('SELECT a.id, a.name, a.date, c.name FROM artist as a, country as c WHERE a.country_id=c.id');
我遇到的问题是,artist.name被country.name覆盖,我在结果中看不到艺术家姓名,只看到国家名称。
如何在CodeIgniter查询构建器下工作?
我使用CodeIgniter版本3。
编辑:添加了更多代码:
$this->db->select('artist.id', 'artist.name', 'artist.date', 'country.name', false);
$this->db->from('artist');
$this->db->join('country', 'country.id=artist.country_id');
$artists = $this->db->get();
部分结果:
[0] => stdClass Object
(
[id] => 1
[name] => Macedonia
[date] => 1979-10-10
)
[1] => stdClass Object
(
[id] => 2
[name] => Britain
[date] => 2003-01-01
)
结果中没有艺术家姓名。国家/地区名称将覆盖此字段。
答案 0 :(得分:2)
你可以编写如下子查询
$this->db->
select('a.id, a.name, a.date, c.name')
->from('artist as a, country as c ')
->where('a.country_id','c.id');
您也可以使用joins
$this->db->select('a.id as artist_id, a.name as artist_name, a.date as artist_date, c.name as country_name',false)
$this->db->from('artist as a')
$this->db->join('country as c','a.country_id = c.id');
访问值。
$行级别> artist_id
$ row-> artist_name等...