gpt4 book ai didi

mysql - 使用 codeigniter 和 mysql 选择、计数和位置

转载 作者:可可西里 更新时间:2023-11-01 06:35:01 24 4
gpt4 key购买 nike

我有两个表如下:

- tblSaler

SalerID | SalerName |
----------------------|
1 | sothorn |
----------------------|
2 | Daly |
----------------------|
3 | Lyhong |
----------------------|
4 | Chantra |
----------------------|

- tblProduct

ProductID | Product | SalerID |
--------------------------------|
1 | Pen | 3 |
--------------------------------|
2 | Book | 2 |
--------------------------------|
3 | Phone | 3 |
--------------------------------|
4 | Computer | 1 |
--------------------------------|
5 | Bag | 3 |
--------------------------------|
6 | Watch | 2 |
--------------------------------|
7 | Glasses | 4 |
--------------------------------|

我需要的结果是:

sothorn | 1
Daly | 2
Lyhong | 3
Chantra | 1

我已经试过了:

    $this->db->select('count(SalerName) as sothorn where tblSaler.SalerID = 1, count(SalerName) as Daly where tblSaler.SalerID = 2, count(SalerName) as Lyhong where tblSaler.SalerID = 3, count(SalerName) as Chantra where tblSaler.SalerID = 4');
$this->db->from('tblSaler');
$this->db->join('tblProduct', 'tblSaler.SalerID = tblProduct.SalerID');

最佳答案

You can use this query for this

SELECT
tblSaler.SalerName,
count(tblProduct.ProductID) as Total
FROM tblSaler
LEFT JOIN tblProduct
ON tblProduct.SalerID = tblSaler.SalerID
GROUP BY tblSaler.SalerID

And here is the active record for this

$select =   array(
'tblSaler.SalerName',
'count(tblProduct.ProductID) as Total'
);
$this->db
->select($select)
->from('tblSaler')
->join('tblProduct','Product.SalerID = tblSaler.SalerID','left')
->group_by('tblSaler.SalerID')
->get()
->result_array();

Demo

输出

_____________________
| SALERNAME | TOTAL |
|-----------|-------|
| sothorn | 1 |
| Daly | 2 |
| Lyhong | 3 |
| Chantra | 1 |
_____________________

关于mysql - 使用 codeigniter 和 mysql 选择、计数和位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19627475/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com