good_evening
good_evening

Reputation: 21749

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.

Upvotes: 0

Views: 57

Answers (2)

Alec
Alec

Reputation: 9078

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.

Upvotes: 0

OMG Ponies
OMG Ponies

Reputation: 332571

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.

Upvotes: 3

Related Questions