GROUP_CONCAT在子查询中不起作用

时间:2015-03-31 05:10:08

标签: mysql

我已尝试此查询以获取以下数据

SELECT 
  GROUP_CONCAT( sb.p_id ) , 
  TRUNCATE( SUM( sb.total_amount ) , 2 ) grand_total, 
  TRUNCATE( SUM( sb.amount_wot ) , 2 ) sale_amount, 
    (SELECT TRUNCATE( SUM( (item_qty * item_price) * tax_price /100 ) , 2 ) 
      FROM ci_bill_items
        WHERE bill_id IN ( GROUP_CONCAT( sb.p_id ) ) ) tax_amount
FROM ci_suppliers_bills sb
  WHERE sb.p_id >0

我得到了预期的结果,但没有tax_amount返回null但是如果我运行单独的查询,如:

SELECT TRUNCATE( SUM( (item_qty * item_price) * tax_price /100 ) , 2 ) 
    FROM ci_bill_items
    WHERE bill_id IN ( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 71 ) 

然后我得到了正确的结果。但是我想在一个查询中像第一个查询一样,group_concat不能像我尝试bill_id IN ( GROUP_CONCAT( sb.p_id ) )那样工作吗?帮助很多。

2 个答案:

答案 0 :(得分:1)

您可以像这样使用FIND_IN_SET

SELECT 
  GROUP_CONCAT( sb.p_id ) , 
  TRUNCATE( SUM( sb.total_amount ) , 2 ) grand_total, 
  TRUNCATE( SUM( sb.amount_wot ) , 2 ) sale_amount, 
    (SELECT TRUNCATE( SUM( (item_qty * item_price) * tax_price /100 ) , 2 ) 
      FROM ci_bill_items
        WHERE FIND_IN_SET(bill_id, GROUP_CONCAT( sb.p_id ) ) > 0 ) tax_amount
FROM ci_suppliers_bills sb
  WHERE sb.p_id >0

答案 1 :(得分:1)

GROUP_CONCAT没有返回列表,它返回一个字符串。要获取可以与IN一起使用的列表,您需要运行子查询:

WHERE bill_id IN (SELECT p_id FROM ci_suppliers_bills
                  WHERE p_id > 0)