Php 如何使用CodeIgniter中的查询生成器从两个表中选择数据?

Php 如何使用CodeIgniter中的查询生成器从两个表中选择数据?,php,mysql,codeigniter,Php,Mysql,Codeigniter,我有这个查询,它在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。每一位艺术家都属于某个国家,并且在其表格中有一个国家id。我需要为艺术家获取数据,但也需要用其适当的名称替换

我有这个查询,它在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。每一位艺术家都属于某个国家,并且在其表格中有一个国家id。我需要为艺术家获取数据,但也需要用其适当的名称替换国家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');
您还可以使用
联接来执行此操作

$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->艺术家姓名等

查找查询生成器的join方法使用join测试代码,我只得到艺术家的id。我还在问题中添加了更多的代码。由于连接函数接受两个参数,因此出现错误。Artister.country_id是来自country的外键,即country.idi有点混淆。如果两者都是外键,则连接返回所需结果。您不需要使用
where
条件。我仍然只获得id,并且缺少其他字段。需要调查。