我有这个查询在 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、姓名和日期,然后用国家表中的适当名称替换国家的 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
)
结果中没有歌手姓名。国家/地区名称会覆盖此字段。
您可以如下编写子查询
$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');
访问值。
$row->artist_id
$row->artist_name 等等...
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句