Mysql 转换为单选查询

标签 mysql sql select mysql-5.7

我有以下数据库(还有更多行):

enter image description here

有些日期和时间我可能只有温度、或x轴振动或任何字段。某些时间戳(如这张图片中的时间戳)缺少诸如 Z 轴振动

之类的字段

我想以以下格式获取所有这些数据,并将未找到的字段转换为“NA”

enter image description here

我尝试了以下查询:

select entry_date, entry_time, field_name, ifnull(value, "NA") as value
from tablename 
where group_name = "SL1-DSM-1" and 
concat(entry_date, " ", entry_time) in 
    ( select distinct(concat(entry_date, " ", entry_time)) 
    from tablename 
    where timestamp(entry_date, entry_time) between "2019-07-22 00:00:00" and 
        "2019-07-23 00:00:00" ) and 
    field_name in (select distinct(field_name) from tablename where group_name = 
        "SL1-DSM-1");

这给了我结果:

enter image description here

有没有办法使用单个查询来实现这一点?或者至少没有。查询,以便加快速度。

注意:目前,我对每个组和字段使用不同的查询,并将它们编译成通用格式,但我希望这是否可以返回我的 MySQL 本身

最佳答案

您可以使用交叉联接生成所有行,然后填写缺失的值。 'N/A' 不是一个好的填写,因为它是一个字符串。只需使用NULL

类似这样的事情:

select entry_date, entry_time, group_name, field_name,
       t.value
from (select distinct entry_date, entry_time, group_name
      from tablename 
     ) dtg cross join
     (select distinct field_name
      from tablename
     ) f left join
     tablename t
     using (entry_date, entry_time, group_name, field_name)

关于Mysql 转换为单选查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57232463/

相关文章:

Android:从数据库中获取特定行

java - mysql 中的登录表单

mysql - 将一个表中的多个列连接到另一个表中的单个列

Python sqlite3 如果 executemany() 中途遇到完整性错误会怎样?

sql-server - 使用 select into where notists 查询时出现 SQL 错误

php - 使用 'optgroup' 选项选择下拉 PHP foreach 循环

javascript - 如何隐藏单个选择的jquery搜索?

java - 准备好的语句仅更新 Jtextfields 中的某些字段

mysql - 奇怪的 MySQL SELECT 执行时间

php - Laravel 获取最近加入表的日期