Which MySQL JOIN query is more efficient?

后端 未结 4 633
谎友^
谎友^ 2021-02-03 16:01

Given the following table structure:

CREATE TABLE user (
   uid INT(11) auto_increment,
   name VARCHAR(200),
   PRIMARY KEY(uid)
);
CREATE TABLE user_profile(
          


        
4条回答
  •  囚心锁ツ
    2021-02-03 16:21

    Looking at the explain queries for these selects, we get this: (row headers are id, select_type, table, type, possible_keys, key, key_len, ref, rows, extra)

    1   SIMPLE  u   system  PRIMARY NULL    NULL    NULL    1   
    1   SIMPLE  p   const   PRIMARY,address PRIMARY 4   const   1   
    

    And the EXPLAIN for the second...

    1   PRIMARY u   system  PRIMARY NULL    NULL    NULL    1   
    1   PRIMARY   system  NULL    NULL    NULL    NULL    1    
    2   DERIVED p   ref address address 201     1   Using where
    

    So, the first query is simpler, and simpler is usually more efficient.

    However, from your CREATEs, it would be vastly more efficient to add the address field to the user table. Since profile is 1-to-1 with the user table (on uid), it is possible to combine the tables and still keep the schema normalized.

    Then, your query would be

    SELECT u.name FROM user u WHERE u.address = 'some constant'
    

    and the explain shows

    1   SIMPLE  u   ref address address 201 const   1   Using where, using filesort
    

    Oddly, the simplified schema uses filesorting, which is bad if you have lots of rows.

    More on explain: http://dev.mysql.com/doc/refman/5.0/en/explain.html

提交回复
热议问题