【问题标题】:Join 3 table group by month按月加入 3 个表组
【发布时间】:2018-08-15 14:50:44
【问题描述】:

我是 Mysql 的新手。我想制作一个基于数据库的图表。我有 3 个表:发票、采购和月份。我想加入所有这些并按月分组。 我已经加入了 2:发票和月份以及购买和月份。有效。但是当我尝试加入其中 3 个时,出现了错误。 下面是我的代码。

function get_chart(){

    $query = $this->db->query("SELECT month.month_name as month, 
        SUM(table_purchase.subtotal) AS total1,
        SUM(table_invoice.subtotal) AS total2  
        FROM month 
        LEFT JOIN table_purchase ON (month.month_num = MONTH(table_purchase.date_pur)  
        LEFT JOIN table_invoice ON (month.month_num = MONTH(table_invoice.date_inv)

        GROUP BY month.month_name ORDER BY month.month_num");

    $res = array();

        foreach($query->result_array() as $data){
            $res[] = array(
                "month" => $data['month'],
                "total1" => $data['total1'],
                "total2" => $data['total2'],
            );
        }
        return $res;

}

错误: 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 6 行的“LEFT JOIN table_invoice ON (month.month_num = MONTH(table_invoice.date_inv)”附近使用正确的语法

【问题讨论】:

  • 更新您的问题并添加您确切的错误消息
  • 完成。我已经对其进行了编辑并添加了错误消息
  • 我已经发布了一个 asnwer ..检查正确的 sintax
  • 谢谢!非常感谢您的帮助!

标签: mysql codeigniter join left-join


【解决方案1】:

查看您的代码,您在 ON 子句的开头有一个错误的 ( .. 尝试删除

$query = $this->db->query("SELECT month.month_name as month, 
    SUM(table_purchase.subtotal) AS total1,
    SUM(table_invoice.subtotal) AS total2  
    FROM month 
    LEFT JOIN table_purchase ON month.month_num = MONTH(table_purchase.date_pur)
    LEFT JOIN table_invoice ON month.month_num = MONTH(table_invoice.date_inv)

    GROUP BY month.month_name 
    ORDER BY month.month_num");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-26
    • 2013-10-17
    • 2019-08-16
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多