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


  (id,月份,购买,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


注意上面列名的使用。我已经尝试过了,结果总是为目标列返回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

关于mysql - 在子查询中动态设置列名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27901290/

10-14 06:30