mysql - 在 MySQL 中获取上个月未保留的用户

标签 mysql select

我正在使用 MySQL 数据库并且我有两个表。它们是 UserReservation

这是我的问题。

  1. 目前,我使用LEFT JOINNOT EXIST 的 SubQuery 呢?从性能的角度来看,哪个更好?
  2. 我可以为这个查询创建 View 吗,这对性能有什么影响吗

用户

| FIELD |        TYPE | NULL | KEY | DEFAULT |          EXTRA |
|-------|-------------|------|-----|---------|----------------|
|   uid |     int(11) |   NO | PRI |  (null) | auto_increment |
| uname | varchar(30) |  YES |     |  (null) |                |

预订

|    FIELD |      TYPE | NULL | KEY |           DEFAULT |          EXTRA |
|----------|-----------|------|-----|-------------------|----------------|
|      rid |   int(11) |   NO | PRI |            (null) | auto_increment |
|      uid |   int(11) |  YES | MUL |            (null) |                |
| reserved | timestamp |   NO |     | CURRENT_TIMESTAMP |                |

SQL 代码:

create table user (
 uid int not null auto_increment,
 uname varchar(30),
 primary key(uid)
);

create table reservation (
 rid int not null auto_increment,
 uid int,
 reserved timestamp not null default CURRENT_TIMESTAMP,
 primary key(rid),
 foreign key (uid) references user (uid)
)

我当前的工作 SQL 查询

SELECT u.uid, u.uname, date_format(reserved, '%Y%m')  
FROM user as u 
LEFT JOIN reservation as r on  
r.uid = u.uid and date_format(reserved, '%Y%m') = 201307  
where r.uid is null  

最佳答案

这是一篇关于性能差异的优秀文章:NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: MySQL

总结:

...the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.

但是您可以通过在保留列上放置索引并像这样重写查询来稍微提高性能:

reserved >= '2013-07-01 00:00:00' AND reserved < '2013-08-01 00:00:00'

View 不会改变查询的任何性能。

关于mysql - 在 MySQL 中获取上个月未保留的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18484297/

相关文章:

php - 如何使用 PHP API 和 AngularJS 2 服务正确处理/获取正确的 JSON 响应?

mysql - 可视化管理表数据的简便方法

for-loop - "Select"goroutine 内的 for 循环语句

PHP/MySQL : How to modify working Select when the result is always one row

mysql - MySQL 立即返回新插入的行以供 GraphQL 使用的正确方法?

mysql - 应用 LIMIT 之前选择子查询的计数(clickhouse)

mysql - 在 MySQL 中更新 2 列的多行

php - mysql_fetch 无法收集数据库中的所有数据

ruby-on-rails - 如何使用simple_form创建分组的选择框?

mysql - 选择...分组依据