这是必要的表格结构
桌子底座

id(**PK**)|name|foreign_code(**FK**)|
1|abcd|102|CAD|
2|efgh|201|CAM|
2|akdl|202|CAM|

表1核心
id(**PK**)|name|class_code|response_code|
101|object1_1|cl101|res101|
102|object1_2|cl102|res102|

表四芯2
id(**PK**)|name|class_code|response_code|
201|object2_1|cl201|res201|
202|object2_2|cl202|res202|

我在MYSQL中的要求是,我需要从下面的任意两个表中随机选择公共匹配的类代码:
SELECT TB.*,core.class_code
FROM table_base as TB
IF (TB.foreign_code=="CAD")
 INNER JOIN table_core1 AS core ON(TB.foreign_code=core.id)
ENDIF

ELSE
 INNER JOIN table_core2 AS core ON(TB.foreign_code=core.id)
ENDELSE

最佳答案

您可以联接两个表并使用COALESCE获取值:

SELECT
    TB.*,
    COALESCE(core1.class_code,core2.class_code) as class_code
FROM table_base as TB
LEFT JOIN table_core1 AS core1 ON TB.foreign_code = core1.id AND TB.foreign_code = 'CAD'
LEFT JOIN table_core2 AS core2 ON TB.foreign_code = core2.id AND TB.foreign_code != 'CAD'

关于mysql - 如何从两个或多个具有相同别名的表中选择数据在mysql中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50344135/

10-13 04:48