如何在我的MYSQL中遍历动态子查询的结果

时间:2019-06-24 09:01:52

标签: mysql correlated-subquery

我需要在子查询中进行迭代,以便在主选择查询中显示动态列。

我已尝试根据以下参考资料应用动态数据透视表:Dynamically create columns from rows in MySQL

但是我需要一种更简洁的方法,因为后续示例也是用于返回我也需要使用的多列条件的子查询。

我想以动态方式为每个tax_id选择tax_amount,并根据其id对其进行命名。

select x.invoice_item_id,

       IFNULL(MAX(CASE WHEN (x.tax_id = 1) THEN x.tax_amount ELSE NULL END), NULL) AS tax_id_1,
       IFNULL(MAX(CASE WHEN (x.tax_id = 2) THEN x.tax_amount ELSE NULL END), NULL)         AS tax_id_2,
       IFNULL(MAX(CASE WHEN (x.tax_id = 3) THEN x.tax_amount ELSE NULL END), NULL)         AS tax_id_3
#   .
#   .
#   .
# for each existing tax from tax table results
from (select t.id from taxes t where t.deleted_at is null) as tax,
     invoice_items ii
       left join invoice_item_tax x on ii.id = x.invoice_item_id
where ii.deleted_at is null
  and x.deleted_at is null
group by invoice_item_id;

0 个答案:

没有答案