[英]MySQL select with INNER JOIN and CASE WHEN in INNER JOIN
I have a data base with Characters. 我有一个字符数据库。 Since Names of the Characters are not only use once the Names are seperate from the Characters.
由于不仅要使用字符名称,还必须将名称与字符分开。 Since there are
Male
and Female
characters I keep these in diffent Tables: 由于存在
Male
和Female
角色,因此将它们保留在不同的表中:
tbl_player, tbl_maleName, tbl_femaleName
tbl_player,tbl_maleName,tbl_femaleName
In my MySQL Select
query i'd like to Select the correct tables with an INNER JOIN
depending on what gender they have. 在我的MySQL
Select
查询中,我想根据其性别选择带有INNER JOIN
的正确表。 So something like this: (The SQL query is wrong and doesn't work :( ) 所以是这样的:(SQL查询是错误的,不起作用:()
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)
Thanks in advance! 提前致谢!
Why you have chosen to use 2 tables for names I'm not certain, but I would not recommend it. 为什么您选择使用2个表作为我不确定的名称,但我不建议这样做。
However, try this: 但是,请尝试以下操作:
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'
You need to use Union and create a value tableOption, with a default value: 您需要使用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'
If the value is female, then the values of the second table will be chosen. 如果值为女性,则将选择第二个表的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.