我正在从3个表格,案例,计算和职位中进行选择。从我需要用另外一个参数分配结果的位置,它是修复方法。下面的代码看起来很好,实际上它也显示我的结果,但没有这个修复方法过滤器。
当前代码和文本结果如下:
SELECT c.vin, c.case_id, c.axrmrs_id, c.date_created,
cl.totalcosts, cl.laborhours, cl.calculationdate, cl.laborcosts,
group_concat(DISTINCT po.text) as text
FROM axnmrs_cases AS c
LEFT JOIN axnmrs_calculations as cl on c.case_id = cl.case_id
LEFT JOIN axnmrs_positions as po on c.case_id = po.case_id
WHERE c.vin='U5YFF24128L064909'
GROUP BY c.vin, c.case_id, c.axrmrs_id
结果(只是文字部分)
-------------------------------
| id | text |
-------------------------------
| 2 | text1,text2,text3 |
-------------------------------
| 3 | text4,text5,text6 |
-------------------------------
它应该如何:
--------------------------------------------------
| id | textA | textB |
--------------------------------------------------
| 22 | tex1, text2 | text3 |
--------------------------------------------------
| 23 | text5 | text4 |
--------------------------------------------------
textA = SELECT text FROM axnmrs_positions WHERE repairmethod LIKE 'L%'
textB = SELECT text FROM axnmrs_positions WHERE repairmethod LIKE 'E%'
我尝试了类似的东西,我怎么能让它发挥作用:
MAX(CASE WHEN po.repairmethod = E THEN po.text) AS 'E'
有人可以帮我这个吗?
编辑: Fiddle linke:http://sqlfiddle.com/#!9/a76e9/3
答案 0 :(得分:3)
您可以这样做:
SELECT ...
, ...
, GROUP_CONCAT(DISTINCT IF(po.repairmethod LIKE 'L%',po.text,NULL) ORDER BY 1) AS textA
, GROUP_CONCAT(DISTINCT IF(po.repairmethod LIKE 'E%',po.text,NULL) ORDER BY 1) AS textB
, ...
IF
表达式中的第一个参数被计算为布尔值,如果为真,则第二个参数为return,否则返回第三个参数。 GROUP_CONCAT将忽略NULL值。我还在GROUP_CONCAT中包含了一个ORDER BY,以使返回更具确定性。
如果您熟悉ANSI SQL:IF
函数本质上是CASE
表达式的简写。例如,这个:
IF(a,b,c)
相当于:
CASE WHEN a THEN b ELSE c END
所以这个:
IF(po.repairmethod LIKE 'E%',po.text,NULL)
相当于:
CASE WHEN po.repairmethod LIKE 'E%' THEN po.text ELSE NULL END
(如果需要,CASE表达式允许我们省略ELSE NULL
。)
答案 1 :(得分:2)
http://sqlfiddle.com/#!9/a76e9/9
SELECT c.vin, c.case_id, c.axrmrs_id,
cl.totalcosts, cl.laborhours, cl.laborcosts,
group_concat(IF(po.repairmethod LIKE 'E%',po.text, null)) E,
group_concat(IF(po.repairmethod LIKE 'A%',po.text, null)) A,
group_concat(DISTINCT po.text) as text
FROM axnmrs_cases AS c
LEFT JOIN axnmrs_calculations as cl on c.case_id = cl.case_id
LEFT JOIN axnmrs_positions as po on c.case_id = po.case_id
WHERE c.vin='U5YFF24128L064909'
GROUP BY c.vin, c.case_id, c.axrmrs_id