在子查询中动态设置列名

setting a column name dynamically in a subquery

我有2张桌子。一个叫 购买

(id, month, purchase, storeid)

另一个叫 purchases_targets

(id, storeid, target1,target2, target3, target4, target5, target6, target7, target8, target9, target10, target11, target12)

purchases_targets 中的列名称对应于月份,即第 1 个月的目标 = target1。 规范化这对我来说不是一个选择!!! 我想做的是类似下面的事情。

SELECT DISTINCT

    purchases.month,
    purchases.purchase, 
    CONCAT('target',purchases.month) AS column_name,
    (SELECT 
      column_name 
    FROM purchases_targets
    WHERE storeid = 1) AS 'target'

FROM purchases 
WHERE purchases.storeid = 1

注意上面 column_name 的使用。我试过这个,结果总是 returns target+month 为目标列。我想知道是否有办法在 mysql 中完成这项工作。让我知道是否需要更多信息。谢谢

您可以使用 CASE 表达式根据 month:

选择不同的列
SELECT DISTINCT
    p.month,
    p.purchase,
    CASE p.month
        WHEN 1 THEN pt.target1
        WHEN 2 THEN pt.target2
        ...
        WHEN 12 THEN pt.target12
    END AS target
FROM purchases AS p
JOIN purchases_targets AS pt ON p.storeid = pt.storeid
WHERE p.storeid = 1