MySQL在INNER JOIN中选择INNER JOIN和CASE WHEN

时间:2016-02-15 09:44:59

标签: mysql join

我有一个包含角色的数据库。由于角色的名称不仅仅使用名称与角色分开。由于存在FemaleSelect字符,因此我将这些字符保存在不同的表中:

  

tbl_player,tbl_maleName,tbl_femaleName

在我的MySQL INNER JOIN查询中,我想根据他们的性别选择具有 SELECT tbl_player.id, (CASE tbl_player.gender WHEN 'm' THEN tbl_maleName.name WHEN 'f' THEN tbl_femaleName.name END) as gamerName , tbl_player.gender FROM tbl_player INNER JOIN (CASE tbl_player.gender WHEN 'm' THEN tbl_maleName ON tbl_player.gamerName = tbl_maleName.id WHEN 'f' THEN tbl_femaleName ON tbl_player.gamerName = tbl_femaleName.id END) 的正确表格。所以像这样: (SQL查询错误,不起作用:()

ssh <user>@<host>  "cat <filepath>"|pbcopy 

提前致谢!

2 个答案:

答案 0 :(得分:2)

为什么你选择使用2个表来表示我不确定的名字,但我不推荐它。

然而,试试这个:

SELECT
      tbl_player.id
    , (CASE tbl_player.gender WHEN 'm' THEN tbl_maleName.name WHEN 'f' THEN tbl_femaleName.name END) AS gamerName
    , tbl_player.gender
FROM tbl_player
      LEFT JOIN tbl_maleName ON tbl_player.gamerName = tbl_maleName.id
                  AND tbl_player.gender = 'm'
      LEFT JOIN tbl_femaleName ON tbl_player.gamerName = tbl_femaleName.id
                  AND tbl_player.gender = 'f'

答案 1 :(得分:-1)

您需要使用Union并创建一个值tableOption,其默认值为:

SELECT tbl_player.id FROM tbl_player LEFT JOIN 
(
(SELECT 'male' as tableOption, name FROM tbl_maleName)
UNION
(SELECT 'female' as tableOption, name FROM tbl_femaleName)
) as gamerName 

ON gamerName.this = tbl_player.that
WHERE gamerName.tableOption = 'female' 

如果值为女性,则将选择第二个表的值。