【问题标题】:How to use sum, join, order by and where clause in mysql?如何在mysql中使用sum、join、order by和where子句?
【发布时间】:2018-06-28 02:31:30
【问题描述】:

所以我有两个如下表:

  1. tb_custmap: idCust, idUser
  2. tb_cust:idCust,收入

我想根据 idCust 从 tb_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'' 附近”

请有人帮助我,我已经这样做了 2 天,但仍然找不到合适的。

【问题讨论】:

  • 我还需要总结收入
  • ORDER BY 追随WHERE
  • 它不能工作。如果我将 ORDER BY 放在 where 之后,系统不会将其识别为语法。

标签: mysql sql codeigniter codeigniter-3 codeigniter-query-builder


【解决方案1】:

希望对您有所帮助:

使用 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-data

【讨论】:

    【解决方案2】:

    你应该这样写查询:

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

    注意事项:

    • WHEREFROM 之后和ORDER BY 之前。
    • 使用作为表名缩写的表别名。
    • 限定所有列名(即,使用表别名)。
    • ? 用于idUser 来自的表。
    • :AccMgrID 用于参数。如果您要通过编程语言有效地使用 SQL,您应该学习如何使用参数。

    【讨论】:

      猜你喜欢
      • 2016-04-03
      • 1970-01-01
      • 1970-01-01
      • 2021-09-01
      • 1970-01-01
      • 2011-04-01
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多