join 3表组按月

pieyvz9o  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(310)

我是mysql的新手。我想做一个基于数据库的图表。我有三张表:发票、采购和月份。我想加入他们所有人的行列,按月份分组。我已经加入了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\u invoice on(month.month\u num=month(table\u invoice.date\u inv)”的正确语法

osh3o9ms

osh3o9ms1#

看看你的代码,你有一个错误 ( 在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");

相关问题