MySQL 1241错误

时间:2018-04-07 10:30:31

标签: mysql pivot mysql-error-1241

我有两个独立的查询,它们正在计算特定节日的付款总额。 IN / OUT由ENUM值给出(见下文)。 enter image description here enter image description here

如果我独立运行查询,它会根据所选的 payment_type IN或OUT提供正确的SUM输出。我的问题是当我尝试在一个查询中将它们组合在一起时,为IN / OUT提供2个单独的列,如下所示。

enter image description here

我在MySQL中有错误"操作数应该包含1列"。在我做了一些研究后,我相信子查询是错误的,但我不太确定如何解决它。

提前感谢您的帮助......

TOTAL IN

SELECT
    SUM(`payment`.`pmt_amount`) AS `TOTAL IN`
    , `payment`.`pmt_type`
    , `festival`.`id_festival`
FROM
    payment
    INNER JOIN festival
        ON (`payment`.`id_festival` = `festival`.`id_festival`)
WHERE (`payment`.`pmt_type` LIKE '%IN'
    AND `festival`.`id_festival` = 1);

enter image description here

并完全退出

SELECT
    SUM(`payment`.`pmt_amount`) AS `TOTAL OUT`
    , `payment`.`pmt_type`
    , `festival`.`id_festival`
FROM
    payment
    INNER JOIN festival
        ON (`payment`.`id_festival` = `festival`.`id_festival`)
WHERE (`payment`.`pmt_type` LIKE '%OUT'
    AND `festival`.`id_festival` = 1);

enter image description here

合并

SELECT
  festival.id_festival,
  payment.pmt_amount,
  payment.pmt_type,
  (SELECT
      payment.pmt_type,
      SUM(payment.pmt_amount) AS `TOTAL OUT`
    FROM payment
    WHERE payment.pmt_type LIKE '%OUT'),
  (SELECT
      payment.pmt_type,
      SUM(payment.pmt_amount) AS `TOTAL IN`
    FROM payment
    WHERE payment.pmt_type LIKE '%IN')
FROM payment
  INNER JOIN festival
    ON payment.pmt_amount = festival.id_festival
WHERE festival.id_festival = 1

enter image description here

2 个答案:

答案 0 :(得分:1)

您的子查询必须返回only one column,但您查询返回two column这是错误的尝试下面提到的查询:

SELECT
  festival.id_festival,
  payment.pmt_amount,
  payment.pmt_type,
  (SELECT
      SUM(payment.pmt_amount) AS `TOTAL OUT`
    FROM payment
    WHERE payment.pmt_type LIKE '%OUT') AS `TOTAL OUT`,
  (SELECT
      SUM(payment.pmt_amount) AS `TOTAL IN`
    FROM payment
    WHERE payment.pmt_type LIKE '%IN') AS `TOTAL IN`
FROM payment
  INNER JOIN festival
    ON payment.pmt_amount = festival.id_festival
WHERE festival.id_festival = 1

答案 1 :(得分:1)

您可能只想在此处使用条件聚合:

SELECT
    f.id_festival,
    SUM(CASE WHEN p.pmt_type = 'Payment IN'  THEN p.pmt_amount ELSE 0 END) AS `TOTAL IN`,
    SUM(CASE WHEN p.pmt_type = 'Payment OUT' THEN p.pmt_amount ELSE 0 END) AS `TOTAL OUT`
FROM festival f
INNER JOIN payment p
    ON p.id_festival = f.id_festival
WHERE f.id_festival = 1
GROUP BY
    f.id_festival;

请注意,您的查询仅查看一个节日,但正确表达此问题的方法是GROUP BY,即使我们只想在输出中保留一个组。