【问题标题】:How to select data from two tables with query builder in CodeIgniter?如何使用 CodeIgniter 中的查询生成器从两个表中选择数据?
【发布时间】:2017-02-25 17:48:12
【问题描述】:

我有这个在 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
    )

结果中没有艺术家姓名。国家名称覆盖此字段。

【问题讨论】:

  • 查找查询生成器的join方法

标签: php mysql codeigniter


【解决方案1】:

您可以编写如下子查询

 $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->艺术家 ID
$row->artist_name 等...

【讨论】:

  • 用 join 试过你的代码,我只得到艺术家的 id。我还在问题中添加了更多代码。
  • 我收到错误,因为 join 函数接受两个参数。
  • artist.country_id 是来自国家/地区的外键,即 country.id
  • 我有点困惑。如果两者都是外键,则加入返回作为期望的结果。你不需要使用where 条件。
  • 我仍然只得到 id,其他字段丢失。需要调查。
猜你喜欢
  • 2015-07-29
  • 1970-01-01
  • 1970-01-01
  • 2013-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
  • 2017-11-20
  • 1970-01-01
相关资源
最近更新 更多