MySQL 检查多个条件之间是否具有唯一标识符

标签 mysql sql

我有一个事件列表。

| TABLE: events
| event_id | event_location | event_date |
|----------|----------------|------------|
| 10       | Denver         | 2014-02-01 | *
| 11       | Chicago        | 2014-04-01 | *
| 12       | Denver         | 2014-06-01 | 
| 13       | Seattle        | 2014-08-01 | *
| 14       | Chicago        | 2014-10-01 |
| 15       | Denver         | 2014-11-01 | *

我还有一份位置访问列表,该列表已注明日期。

| TABLE: allowed
| allowed_location | date_begin | date_end   |
|------------------|------------|------------|
| Denver           | 2014-01-01 | 2014-03-01 |
| Chicago          | 2014-03-01 | 2014-05-01 |
| Seattle          | 2014-07-01 | 2014-09-01 |
| Denver           | 2014-10-01 | 2014-12-01 |

我想要找到的是所有 event_id 的 event_date 位于其各自 allowed_location 行(date_begin 和 date_end)之一之间。

第一个表中符合条件的结果用星号表示。

通过以下查询,我可以获得一些结果,但不是我想要的结果:

SELECT event.event_id
FROM event
LEFT JOIN
  (SELECT allowed_location,
          date_begin,
          date_end
   FROM allowed) AS allowed ON allowed.allowed_location=event.event_location
WHERE (event.event_date >= allowed.date_begin)
  AND (event.event_date <= allowed.date_end)

这会给我一些结果,但它只留下连接允许的表中的结果之一。我无法找到一种方法来检查事件的日期是否在该位置允许的任何日期范围之间。

如有任何帮助,我们将不胜感激。

最佳答案

一个简单的JOINreturn a row matching each row combination allowed by the ON condition 。从那里,您只需要过滤掉那些日期不匹配的日期。 (另请注意 BETWEEN 运算符,它使基于范围的比较变得更加简单。)

SELECT e.event_id
FROM events e
    JOIN allowed a ON a.allowed_location = e.event_location
WHERE e.event_date BETWEEN a.date_begin AND a.date_end

这个returns the result you expect .

关于MySQL 检查多个条件之间是否具有唯一标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23233913/

相关文章:

mysql - SQL 查询中的案例?

SQL:选择性子查询

sql - 表索引设计

php - MediaWiki:如何获取用户最近编辑的N篇文章?

java - 如何使用 JPA 从 MySQL 检索 DateTime,无需毫秒

php从数据库加载图像(pdf)

mysql - 按类型/contactid 计算不同的消息

mysql - 列出拥有最多代币的用户

MySQL全文搜索找不到单个拼写错误

php - MySQL外域搜索