MySQL:将同一个表中具有不同列名的多个 WHERE 子句组合在一起

标签 mysql where-clause

我是 MySQL 新手,正在通过 PluralSight 学习。我正在尝试执行一个查询,结果为 4 列。 4 列中的 3 列来自同一列,但通过指向数值的 WHERE 子句进行区分。此外,我还包括来自不同表的一列。我觉得修复很容易,但正如我提到的,我对此很陌生。单独来看,这些部分工作得很好,但我不知道如何正确地加入它们。任何帮助,将不胜感激。迄今为止我的工作包含在下面。

Select answer as FirstName
FROM glpi.glpi_plugin_formcreator_answers
WHERE plugin_formcreator_questions_id = 1

Select answer as MI
FROM glpi.glpi_plugin_formcreator_answers
WHERE plugin_formcreator_questions_id = 54 

Select answer as LastName
FROM glpi.glpi_plugin_formcreator_answers
WHERE plugin_formcreator_questions_id = 55

Select request_date
FROM glpi.glpi_plugin_formcreator_forms_answers

最佳答案

这不是答案

因为我怀疑您在需求中遗漏了一些重要的内容

我只想为您提供一种您想要获得的方法,您唯一缺少的是GROUP BY列。

SELECT
   IF(plugin_formcreator_questions_id = 1,answer, null) as FirstName
   IF(plugin_formcreator_questions_id = 54,answer, null) as MI,
   IF(plugin_formcreator_questions_id = 55,answer, null) as LastName,
   request_date
FROM glpi.glpi_plugin_formcreator_answers
WHERE plugin_formcreator_questions_id IN (1,54,55)

所以最终版本应该是这样的:

SELECT
   form_id,
   MAX(IF(plugin_formcreator_questions_id = 1,answer, null)) as FirstName
   MAX(IF(plugin_formcreator_questions_id = 54,answer, null)) as MI,
   MAX(IF(plugin_formcreator_questions_id = 55,answer, null)) as LastName,
   MAX(request_date)
FROM glpi.glpi_plugin_formcreator_answers
WHERE plugin_formcreator_questions_id IN (1,54,55)
GROUP BY form_id

关于MySQL:将同一个表中具有不同列名的多个 WHERE 子句组合在一起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51787068/

相关文章:

Mysql - 按标签搜索博客

mysql - 为什么 WHERE 子句中具有不同外键的相同 SQL 查询会获得不同的性能?

java - 如何在java中进行整数枚举声明

mysql - 子查询 - W3Resources

c# - where 子句的正则表达式?

python - python 中的函数什么都不返回

php - 使用一个查询进行多个求和查询

mysql - 强制元素在 mysql 查询中的位置

linq - 仅在不为空的情况下,在where子句中使用变量?一种动态的where子句?

mysql - Count() 使用 Where 子句和 Left Join