我正在使用 MySQL
数据库并且我有两个表。它们是 User
和 Reservation
这是我的问题。
- 目前,我使用
LEFT JOIN
与NOT EXIST
的 SubQuery 呢?从性能的角度来看,哪个更好? - 我可以为这个查询创建 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/