mysql,使用大小写和变量压缩查询

时间:2018-10-24 08:27:11

标签: mysql

我有这样的查询:根据CASE选择,对不同的表进行子查询。

SELECT
    ID,
    UNID,
    IDMENU,
    IDTYPE, ( CASE WHEN `IDMENU` = 1 THEN
            (
                SELECT
                    tableB.DESCRIPTION
                FROM
                    tableB
                WHERE
                    tableB.ID = tableA.ID
                    AND tableB.IDMENU = tableA.IDMENU
                    AND tableB.IDTYPE = tableA.IDTYPE)
                WHEN `IDMENU` = 2 THEN
                (
                    SELECT
                        tableC.DESCRIPTION
                    FROM
                        tableC
                    WHERE
                        tableC.ID = tableA.ID
                        AND tableC.IDMENU = tableA.IDMENU
                        AND tableC.IDTYPE = tableA.IDTYPE)
END) AS DESCRIPTION
FROM
    tableA

这可以更紧凑吗?我可以将CASE保存值存储到变量中,然后将该变量用作表名吗?我应该使用一个程序吗?

2 个答案:

答案 0 :(得分:0)

您可以使用Left Join代替子查询。 Left Join将确保主(最左侧)表中的所有行均会出现。

SELECT
    tA.ID,
    tA.UNID,
    tA.IDMENU,
    tA.IDTYPE, 
    (CASE tA.IDMENU
       WHEN 1 THEN tB.DESCRIPTION
       WHEN 2 THEN tC.DESCRIPTION) AS DESCRIPTION 
FROM
    tableA AS tA 
LEFT JOIN tableB AS tB ON tB.ID = tA.ID AND 
                          tB.IDMENU = tA.IDMENU AND 
                          tB.IDTYPE = tA.IDTYPE 
LEFT JOIN tableC AS tC ON tC.ID = tA.ID AND 
                          tC.IDMENU = tA.IDMENU AND 
                          tC.IDTYPE = tA.IDTYPE 

答案 1 :(得分:0)

您可以通过以下情况下的情况尝试以下查询

SELECT
   ID,
   UNID,
   IDMENU,
   IDTYPE,
   case 
     when IDMENU=1 then tableB.DESCRIPTION 
     when IDMENU=2 then tableC.DESCRIPTION 
   end as description
   FROM TableA 
   left join tableB on 
        tableB.ID = tableA.ID AND 
        tableB.IDMENU = tableA.IDMENU AND 
        tableB.IDTYPE = tableA.IDTYPE
   left join tableC on 
        tableC.ID = tableA.ID AND 
        tableC.IDMENU = tableA.IDMENU AND 
        tableC.IDTYPE = tableA.IDTYPE