1

我有两个 mysql 查询,想将它们合并为一个。

这一个基本上将两列“合并”为一列。

SELECT description

CASE 
    WHEN checkbox2 = '2' THEN '2'
    WHEN checkbox2 = '1' THEN '1'
    WHEN checkbox2 = '0' THEN '0'   
    WHEN checkbox1 = '1' THEN '1'
    WHEN checkbox1 = '0' THEN '0' END 'checkbox_merge',

FROM table2 
LEFT JOIN table3 
    ON table2.id2 = table3.id2
ORDER BY table2.id2

这个需要两个表并旋转名称(A->D)并将它们用作列来绘制网格,如果你愿意的话。

SELECT description

  MAX(CASE WHEN column1 = 'A' THEN checkbox1 ELSE '-' END) 'A',
  MAX(CASE WHEN column1 = 'B' THEN checkbox1 ELSE '-' END) 'B',
  MAX(CASE WHEN column1 = 'C' THEN checkbox1 ELSE '-' END) 'C',
  MAX(CASE WHEN column1 = 'D' THEN checkbox1 ELSE '-' END) 'D',

FROM table1
JOIN table2
    ON table2.id = table1.id
WHERE table2.id = var1 and table1.id = var1
GROUP BY description

所以我想采用第一个查询并在第二个查询中使用checkbox_mergein 代替checkbox1

任何想法如何做到这一点?

4

2 回答 2

2

尝试这个:

SELECT 
  description,
  MAX(
    CASE 
        WHEN column1 = 'A' 
        THEN (
            CASE 
                WHEN checkbox2 = '2' THEN '2'
                WHEN checkbox2 = '1' THEN '1'
                WHEN checkbox2 = '0' THEN '0'   
                WHEN checkbox1 = '1' THEN '1'
                WHEN checkbox1 = '0' THEN '0'
            END
        ) 
    ELSE '-' 
    END
  ) 'A'

FROM 
  table1
JOIN table2
    ON table2.id = table1.id
LEFT JOIN table3 
    ON table2.id2 = table3.id2
WHERE 
    table1.id = var1
GROUP BY description
于 2013-05-20T08:16:31.460 回答
2

免责声明:这适用于 SQL Server,不确定 MySQL。只需将第一个查询嵌套在第二个查询中,类似于这个模型:

SELECT description

  MAX(CASE WHEN t2.column1 = 'A' THEN t1.checkbox_merge ELSE '-' END) 'A',
  MAX(CASE WHEN t2.column1 = 'B' THEN t1.checkbox_merge ELSE '-' END) 'B',
  MAX(CASE WHEN t2.column1 = 'C' THEN t1.checkbox_merge ELSE '-' END) 'C',
  MAX(CASE WHEN t2.column1 = 'D' THEN t1.checkbox_merge ELSE '-' END) 'D',

FROM (
    SELECT 
        CASE 
            WHEN checkbox2 = '2' THEN '2'
            WHEN checkbox2 = '1' THEN '1'
            WHEN checkbox2 = '0' THEN '0'   
            WHEN checkbox1 = '1' THEN '1'
            WHEN checkbox1 = '0' THEN '0' 
        END as [checkbox_merge],
        table2.id2 as [id]
    FROM table2 
    LEFT JOIN table3 
        ON table2.id2 = table3.id2
    ORDER BY table2.id2) 
as  t1
JOIN table2 t2
    ON t1.id = t2.id
WHERE t2.id = var1 and t1.id = var1
GROUP BY t2.description
于 2013-05-20T08:25:06.353 回答