SQL SELECT CASE WITH SELECT

时间:2014-02-17 09:07:22

标签: mysql sql select case

我在我的数据库MySQL上有这种情况:

  

TABLE_A
  鳕鱼| Value1 | Value2 | Value3

     

表-B
  鳕鱼| Value4 |值5

     

TABLE_C
  鳕鱼| Value6

我使用此查询:

SELECT
  table_a.value1 AS Number, 
  table_a.value2 AS Date, 
  table_b.name   AS Name, 
  table_b.age    AS Age 
FROM 
  table_a 
  LEFT JOIN table_c 
         ON table_a.cod = table_c.cod 
            AND table_c.value5 = 1 
  LEFT JOIN table_b 
         ON table_c.cod = table_b.cod 
WHERE value3 = 'MY_SEARCH_VALUE' 
ORDER BY table_a.cod ASC 

一切都很好,但现在我必须从TABLE_A中选择元素(与TABLE_B和TABLE_C连接)与TABLE_A上的一个元素连接。

例如,TABLE_A.Cod = 'X'TABLE_A.Cod ='Y'使用上述查询时,相反也选择TABLE_A.Cod ='Z'TABLE_A.Cod = 'ALL_OTHERS_CODE'


修改 :( 从OP的评论中添加):

我的查询结果

SELECT
  TABLE_A.Value1 AS Number,
  TABLE_A.Value2 AS Date,
  TABLE_B.name AS Name,
  TABLE_B.age AS Age
FROM
  TABLE_A
  LEFT JOIN TABLE_C
         ON TABLE_A.Cod = TABLE_C.Cod
            AND TABLE_C.Value5 =1
  LEFT JOIN TABLE_B
         ON TABLE_C.Cod = TABLE_B.Cod
WHERE Value3 = 'DEFENDER'
ORDER BY TABLE_A.Cod ASC  

例如:(12 - 14/01/01 - John - 18

我希望结果更像上面的结果。如果我应该尝试其他代码,例如'DEFENDER_A',我希望:(1214/01/01John18 --- {{1} },514/01/01Frank

1 个答案:

答案 0 :(得分:2)

像这样更改您的代码。

Select
TABLE_A.Value1 AS Number, 
TABLE_A.Value2 AS Date, 
TABLE_B.name AS Name, 
TABLE_B.age AS Age 
FROM TABLE_A LEFT JOIN TABLE_C ON TABLE_A.Cod = TABLE_C.Cod 
AND TABLE_C.Value5 =1 LEFT JOIN TABLE_B ON TABLE_A.Cod = TABLE_B.Cod 
WHERE Value3 = 'DEFENDER' 
ORDER BY TABLE_A.Cod ASC