【问题标题】:Complex Two Table Join复杂的两表连接
【发布时间】:2014-07-23 05:56:48
【问题描述】:

尝试生成每个Sensorrule 行最多有一行的结果集,其中Sensorrule.sensorid 存在于Sensordata.sensorid 中,DATE(Sensor.messagedate) = CURDATE()TIME(Sensordata.messagedate) => Sensorrule.fromtimeTIME(Sensordata.messagedate) => Sensorrule.totime

如果 Sensordata 中没有当前日期 (messagedate) 且时间为 messagedatefromtimetotime 之间的行,则结果集可能少于 Sensorrule 中的行数。

Sensorrule
+-------------+--------------+------------+-------+--------------+
| sensorid    | fromtime     | totime     | msg   | name         |
+-------------+--------------+------------+-------+--------------+
| 27460       | 5:00         | 11:00      | Work  | Bob          |
| 27461       | 4:00         | 15:00      | Not   | Susan        |
| 27460       | 7:30         | 12:00      | Max   | Rick         |
+-------------+--------------+------------+-------+--------------|

Sensordata
+---------+---------------------+---------------+----------+
| Room    | messagedate         | transactionid |  sensorid|
+---------+---------------------+---------------+----------+
| Bedroom | 2014-05-30 07:48:14 | 332243181     | 27460    |
| Bedroom | 2014-05-30 05:48:14 | 332243182     | 27464    |
| Bedroom | 2014-05-22 07:36:21 | 332243183     | 27460    |
| Bedroom | 2014-05-22 09:23:21 | 332656534     | 27464    |
| Bedroom | 2014-05-21 06:34:22 | 332243185     | 27461    |
| Bedroom | 2014-05-20 06:15:06 | 332243187     | 27460    |
| Bedroom | 2014-05-20 07:40:34 | 332243172     | 27465    |
| Bedroom | 2014-05-19 09:27:56 | 332243191     | 27461    |
| Bedroom | 2014-05-18 06:34:08 | 332243101     | 27460    |
+---------+---------------------+---------------+----------+

希望结果集看起来像:

Sensorid    msg     name    
24760       Work    Bob 
27461       Not     Susan

注意:上面的数据集并没有具体产生上述结果

【问题讨论】:

  • 请显示表格结构并告诉我们您要达到的目标是什么?
  • 对不起。当我按下回车键时编辑错误。
  • 你在结果集中想要什么我的意思是选择条件是什么?
  • 如果 Sensorrule 中每一行的 sensorid 在 Sensordata 表的一行或多行中找到今天的日期(messagedate),并且 messagedate 中的时间介于 Sensorrule 的 fromtime 和 totime 之间,则输出 Sensorrule 的 sensorid、MSG 和姓名。如果该条件在 Sensordata 中至少存在一次,我只想在 Sensorrule 中的每一行看到一个行输出(或没有)。

标签: mysql sql


【解决方案1】:
select distinct s.sensorid,s.msg,s.name from sensorrule s,sensordata d
where s.sensorid=d.sensorid and 
time(d.messagedate)>s.fromtime and 
time(d.messagedate)<s.totime;

【讨论】:

  • (MYSQL)ERROR 1271 (HY000): Illegal mix of collat​​ions for operation '>'
  • 在我之前的尝试中也收到此错误消息(因此在这里寻求帮助)
  • 问题出在您的表排序规则类型上。请查看stackoverflow.com/questions/1241856/…
  • 我想我找到了问题所在。将 s.fromtime 和 s.totime 更改为显式日期时间格式:例如STR_TO_DATE(s.totime,'%H:%i') 这允许查询工作。但是我得到了很多结果(Sensordata 中的每一行匹配一个,而不是 Sensorrule 中的每一行只有一个。
  • 对于 Sensorrule 中的每一行,这不是只返回一个结果而不是一个可能的结果吗?
猜你喜欢
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2016-04-04
  • 2016-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-20
相关资源
最近更新 更多