0

我有这个查询:

SELECT COUNT(*) AS invoice_count, IFNULL(SUM(qa_invoices.invoice_total), 0)
AS invoice_total, IFNULL(SUM(qa_invoices.invoice_discount) ,0) AS invoice_discount
FROM qa_invoices
WHERE (DATE(qa_invoices.invoice_date) BETWEEN '12/06/25' AND '12/06/25') 
AND qa_invoices.status_code IN (5, 8)

UNION 

SELECT IFNULL(SUM(qa_returns.client_credit), 0) 
FROM qa_returns 
WHERE (DATE(qa_returns.returnlog_date) BETWEEN '12/06/25' AND '12/06/25');

我得到错误:

The used SELECT statements have a different number of columns.

我正在尝试使用 UNION 命令加入这 2 个选择,如果我们查看returnlog_dateinvoice_date具有相同的数据条件,如果有任何方法可以将两个查询合并为一个会更好。

4

4 回答 4

4

该错误准确地告诉您问题所在,因为UNION您必须在每个查询中具有相同数量的列。

我不确定您的第二个查询中的哪一列对应于您的第一个查询,但您可以在第二个查询中插入一个零。

像这样的东西:

SELECT COUNT(*) AS invoice_count
    , IFNULL(SUM(qa_invoices.invoice_total), 0)  AS invoice_total
    , IFNULL(SUM(qa_invoices.invoice_discount) ,0) AS invoice_discount
FROM qa_invoices 
WHERE (DATE(qa_invoices.invoice_date) BETWEEN '12/06/25' AND '12/06/25') 
    AND qa_invoices.status_code IN (5, 8)

UNION 

SELECT 0
    , IFNULL(SUM(qa_returns.client_credit), 0) 
    , 0
FROM qa_returns 
WHERE (DATE(qa_returns.returnlog_date) BETWEEN '12/06/25' AND '12/06/25');
于 2012-06-26T20:09:20.147 回答
4

使用子选择:

SELECT
    COUNT(*) AS invoice_count,
    IFNULL(SUM(invoice_total), 0) AS invoice_total,
    IFNULL(SUM(invoice_discount), 0) AS invoice_discount,
    (
        SELECT IFNULL(SUM(qa_returns.client_credit), 0)
        FROM qa_returns
        WHERE qa_returns.returnlog_date >= '2012-06-25'
        AND qa_returns.returnlog_date < '2012-06-26'
    ) AS client_credit
FROM qa_invoices
WHERE invoice_date >= '2012-06-25'
AND invoice_date < '2012-06-26'
AND status_code IN (5, 8)
于 2012-06-26T20:10:21.900 回答
1

您联合在一起的结果集必须具有完全相同的列。

于 2012-06-26T20:09:15.707 回答
1

那么为了做一个 UNION 你需要有相同数量的列

于 2012-06-26T20:10:50.017 回答