MYSQL在CodeIgniter

问题描述 投票:0回答:5
Company 1 Company 1 Company 2 Company 3 Company 4 Company 4

但我想下拉返回,
Company 1
Company 2
Company 3
Company 4

我正在使用数据库库和活动记录来编写SQL当前我需要知道我只用什么来显示每个结果一次,

function getAllUsers() {
    $this->db->select('*');
    $this->db->from('userProfileTable');

    $query = $this->db->get();
    return $query->result_array();
}

或RAW SQL是什么?

使用:

$this->db->distinct(); $this->db->select('*'); $this->db->from('userProfileTable'); $query = $this->db->get(); return $query->result_array();
mysql database codeigniter
5个回答
3
投票

您可以使用the
$this->db->distinct();
在查询中添加

1
投票
关键字。

将您的功能调整为此:

function getAllUsers() {
    $this->db->distinct();
    $query = $this->db->get('userProfileTable');

    return $query->result_array()
}
生产

SELECT DISTINCT * FROM userProfileTable

请注意,
select

from

已从您的原始功能中删除,因为
get
只是做同样的事情。

使用独特的关键字:
SELECT DISTINCT * from userProfileTable;
    

this应该做到的技巧:

0
投票
function getAllUsers() { $this->db->distinct(); $query = $this->db->get('userProfileTable'); return $query->result_array(); }

您没有共享任何示例数据库表数据,因此我们不100%知道您的行是否具有共享公司名称的行是否在其他列中可能具有唯一的值。  这很重要,因为如果其他列具有唯一的值,那么仅在 *之前就添加不同的 *将无法工作。  如果全行是相同的,那么我会说您的数据存储策略有缺陷。
使用

0
投票

public function getUniqueUsers(): array { return $this->db ->distinct() ->get('userProfileTable') ->result_array(); }
使用

0
投票

public function getUniqueUsers(): array { return $this->db ->distinct() ->select('id, name') ->get('userProfileTable') ->result_array(); }

如果使用
GROUP BY

,请提名选择子句中的分组列,因为当期望聚合功能时,
*
会引起麻烦。 使用

SELECT id, name FROM userProfileTable GROUP BY id, name

public function getUniqueUsers(): array { return $this->db ->select('id, name') ->group_by('id, name') ->get('userProfileTable') ->result_array(); }
最终可能存在性能后果,因此请阅读此信息以进行进一步的见解:

更快的速度,在mysql中选择独特的或分组?
    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.