如何在mysql中使用sum、join、order by和where子句?

d8tt03nd  于 2021-06-24  发布在  Mysql
关注(0)|答案(2)|浏览(323)

我有两张表,如下所示:
tb\u custmap:idcust,iduser
tb\u cust:idcust,收入
我想从基于idcust的tb\u cust获得收入,并且只从特定的iduser获得收入。我试过这个:

SELECT tb_cust.revenue
FROM tb_custmap INNER JOIN
     tb_cust
     ON tb_custmap.idCust = tb_cust.idCust
ORDER BY tb_cust.revenue
WHERE idUser='".$AccMgrID."'

但我犯了个错误
“您的sql语法有错误;请查看与您的mariadb服务器版本相对应的手册,以获取在第1行“where iduser='azkyath'”附近使用的正确语法
请帮帮我,我已经做了两天了,还是找不到合适的。

sxpgvts3

sxpgvts31#

您应该这样编写查询:

SELECT c.revenue
FROM tb_custmap cm INNER JOIN
     tb_cust c
     ON cm.idCust = c.idCust
WHERE ?.idUser = :AccMgrID
ORDER BY c.revenue;

笔记: WHERE 追求 FROM 在那之前 ORDER BY .
使用表名缩写的表别名。
限定所有列名(即使用表别名)。
这个 ? table在哪里 idUser 来自。 :AccMgrID 用于参数。如果要从编程语言中有效地使用sql,应该学习如何使用参数。

ijxebb2r

ijxebb2r2#

希望这能帮助您:
使用ci查询生成器执行此操作

/*if you want to use `sum` use this instead of select
 $this->db->select_sum('tb_cust.revenue');

* /

$this->db->select('tb_cust.revenue');
$this->db->from('tb_custmap');
$this->db->join('tb_cust' , 'tb_cust.idCust = tb_custmap.idCust');

/*In where clause replace `table` name also with the correct table name 
 from where `idUser` column belongs to

* /

$this->db->where('table.idUser', $AccMgrID);

$this->db->order_by('tb_cust.revenue','ASC');
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
    print_r($query->result());
}

更多信息:https://www.codeigniter.com/user_guide/database/query_builder.html#selecting-数据

相关问题