【问题标题】:CodeIgniter PHP - How to choose which ID to select in a join while using "select *"CodeIgniter PHP - 如何在使用“select *”时选择在连接中选择哪个 ID
【发布时间】:2013-08-06 13:32:18
【问题描述】:

基本上,我有这样的编码约定,即任何作为 ID 的主键,我都会将列名称为“id”。所以我的问题来了。我正在加入两个表,我得到的是第二个表的 ID,而不是第一个表。我知道如果我使用 select "artists.id, ..." 它会起作用,但我想知道是否有使用 "select *" 的修复,这对于未来的扩展会更好(新的列将会出现......) .

这是我的模型:

$this->db->select('*');
$this->db->from('artists');
$this->db->join('categories', 'artists.category_id = categories.id');
$this->db->where('id', $id);
$this->db->limit(1);

使用 Print_R,我可以看到我正在获取所有列(但只有 1 个 id,它来自类别表而不是艺术家表),没有任何表前缀。

【问题讨论】:

  • 没有。避免使用“SELECT *”。

标签: php mysql codeigniter select join


【解决方案1】:

您应该使用表别名来限定您的列

$this->db->select('a.id as artist_id, c.id as category_id, a.column2,c.column3');
$this->db->from('artists a');
$this->db->join('categories c', 'a.category_id = c.categories.id');
$this->db->where('a.id', $id);
$this->db->limit(1);

如果您想继续使用SELECT *

$this->db->select('a.*, c.*, a.id as artist_id, c.id as category_id');
$this->db->from('artists a');
$this->db->join('categories c', 'a.category_id = c.categories.id');
$this->db->where('a.id', $id);
$this->db->limit(1); 

请记住,将返回最后一个重复列。因此,a.*,c.* 将返回 c.id 作为 idc.*,a.* 将返回 a.id 作为 id

【讨论】:

  • 打败我。好答案
  • 您可以随时编辑我的答案并添加一些链接以供参考;)
  • 嗯,我知道:D。我想知道是否有办法使用“select *”:P。所以我猜没有?
  • @KevinVanRyckegem:不使用 MySQL。
  • 好的,谢谢你的信息!我知道最好不要使用 select *,但我总是想知道是否还有其他我不知道的方法:)。
【解决方案2】:

我想为了省去你的麻烦,为了将来,总是使用列名前面的表格。 这里没有逻辑,当您查找 * 时,它表示所有字段,例如在 Oracle 中,您将获得所有字段以及前面的表,我猜在 MySQL 中不会,但如果我是你,我不会冒险它。

【讨论】:

    猜你喜欢
    • 2016-08-09
    • 1970-01-01
    • 2015-10-24
    • 2016-05-18
    • 1970-01-01
    • 2023-03-17
    • 2019-04-02
    • 1970-01-01
    • 2015-05-18
    相关资源
    最近更新 更多