我有两个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_merge
代替checkbox1
。
任何想法如何实现这一目标?
答案 0 :(得分: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
答案 1 :(得分: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