简体   繁体   English

SELECT 时的 MySQL CASE

[英]MySQL CASE when SELECT

I have the following query:我有以下查询:

SELECT CASE WHEN `def_spell`.`type` = 0 THEN `spells_damage`.* 
            WHEN `def_spell`.`type` = 1 THEN `spells_weaken`.*
       END 
FROM `def_spell` 
LEFT JOIN `spells_damage` ON `def_spell`.`id` = `spells_damage`.`spell_id` 
LEFT JOIN `spells_weaken` ON `def_spell`.`id` = `spells_weaken`.`spell_id` 
WHERE `def_spell`.`id` = 1;

Hopefully that makes sense... I'm basically trying to select everything from spells_damage providing type is 0 and everything from spells_weaken providing type is 1.希望这是有道理的......我基本上试图从spells_damage提供type选择所有内容为0,从spells_weaken提供type选择所有内容为1。

I'd also like to select everything from def_spell regardless. def_spell我还想从def_spell选择所有内容。

Can someone please fix the query?有人可以修复查询吗? I've never used cases like this before and not sure how to.我以前从未使用过这样的案例,也不知道如何使用。

You can't use a CASE to choose between the output of the two tables like that.您不能使用 CASE 在这样的两个表的输出之间进行选择。

Unfortunately, that's the easy bit;不幸的是,这很容易。 working out (a) what you're trying to do and (b) achieving an equivalent result is going to take a little longer.解决 (a) 您正在尝试做的事情和 (b) 获得相同的结果将需要更长的时间。

It would be easier if you gave us information about the columns in the Spells_Weaken and Spells_Damage table.如果您向我们提供有关 Spells_Weaken 和 Spells_Damage 表中列的信息会更容易。 Presumably, there are some differences;据推测,存在一些差异; otherwise, you'd have a single table.否则,您将只有一张桌子。 Indeed, a single Spells table might still be a better design.实际上,单个 Spells 表可能仍然是更好的设计。

Let's put doubts aside.让我们把怀疑放在一边。 Assuming that the Spells_Weaken and Spells_Damage tables are UNION-compatible, you can use a UNION to achieve the result:假设 Spells_Weaken 和 Spells_Damage 表是 UNION 兼容的,您可以使用 UNION 来实现结果:

SELECT s.*, d.*
  FROM def_spell AS s
  LEFT JOIN spells_damage AS d ON s.id = d.spell_id
 WHERE s.type = 0
   AND s.id = 1
UNION
SELECT s.*, w.*
  FROM def_spell AS s
  LEFT JOIN spells_weaken AS w ON s.id = w.spell_id 
 WHERE s.type = 1
   AND s.id = 1;

You won't be able to do that.你将无法做到这一点。 You will need to either split it into two queries, or manually specify each of the columns with the CASE statement.您需要将其拆分为两个查询,或者使用CASE语句手动指定每一列。

SELECT CASE WHEN a.`type` = 0 THEN b.col1 
            WHEN a.`type` = 1 THEN c.col1
       END  AS col1
       , CASE WHEN a.`type` = 0 THEN b.col2
            WHEN a.`type` = 1 THEN c.col2
       END  AS col2
FROM `def_spell`  a
LEFT JOIN `spells_damage` b ON a.`id` = b.`spell_id` 
LEFT JOIN `spells_weaken` c ON a.`id` = c.`spell_id` 
WHERE a.`id` = 1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM