4

我正在使用MySQL数据库,我有两个表。他们是User并且Reservation

这是我的问题。

  1. 目前,我将LEFT JOINSubQuery 与NOT EXIST. 从性能的角度来看,哪个更好?
  2. 我可以为此查询创建视图吗,这会对性能产生任何影响吗

用户

| 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  
4

4 回答 4

2

Here's an excellent article about performance differences: NOT IN vs. NOT EXISTS vs. LEFT JOIN / IS NULL: MySQL

Summary:

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

But you can improve performance a little by putting an index on reserved column and rewriting your query like this:

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

Views don't change anything of the performance of the query.

于 2013-08-28T09:43:22.883 回答
1

问题是,如果你做了一个date_formatMySQL 索引是没有用的。你应该使用这样的东西:

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

比使用索引,您的查询会更快。如果您在表预订上有一个组合索引,带有字段,uid, reserved

于 2013-08-28T09:40:56.200 回答
0

如果不存在,这会更好。

SELECT u.uid, u.uname, date_format(reserved, '%Y%m')  
FROM user as u where not exist (select 1 from reservation as r   
where r.uid = u.uid and date_format(reserved, '%Y%m') = 201307)

视图对性能没有多大帮助。它主要关注可重用性、数据隐藏和安全原因。

于 2013-08-28T09:40:17.530 回答
0

You'll want to use NOT EXISTS, and making a view won't really do much for you, even convenience wise since this is a pretty simple query.

Also see: SQL performance on LEFT OUTER JOIN vs NOT EXISTS

于 2013-08-28T09:42:08.347 回答