简体   繁体   中英

How to optimize this query more?

    SELECT mem.name, 
           mem.regdate, 
           stat.level
      FROM stats AS stat
INNER JOIN members AS mem
     WHERE stat.id = mem.id 
       AND mem.ref = {$members['id']}

stats and members table has index on id . But when I run query it checks all rows in stats table (in members table it takes only one). Any ideas what I am doing wrong? Thanks.

Use correct ANSI-92 JOIN syntax - JOIN criteria is specified in the ON clause:

SELECT mem.name, 
       mem.regdate, 
       stat.level
  FROM stats AS stat
  JOIN members AS mem ON mem.id = stat.id 
 WHERE mem.ref = {$members['id']}

Without the JOIN criteria, MySQL will return a cartesian product and then apply the WHERE clause to those results. Pretty much any other database would tell you that you have a syntax error for the query you provided.

Also, the INNER keyword is optional.

Try selecting from the main table (in this case members, I persume) and JOIN with stats for additional information. Use ON to define how stats is connected to members, and use WHERE to limit the results from the member table.

SELECT mem.name, mem.regdate, stat.level
FROM members AS mem
INNER JOIN stats AS stat
  ON stat.id = mem.id
WHERE mem.ref = {$members['id']}

Since it's an INNER JOIN you can turn it around as well (selecting from stats, joining on members), but this probably makes more sense given you're looking at a certain member.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM