简体   繁体   English

如何进一步优化此查询?

[英]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 . statsmembers表的索引为id But when I run query it checks all rows in stats table (in members table it takes only one). 但是,当我运行查询时,它会检查stats表中的所有行(在members表中只需要一行)。 Any ideas what I am doing wrong? 有什么想法我做错了吗? Thanks. 谢谢。

Use correct ANSI-92 JOIN syntax - JOIN criteria is specified in the ON clause: 使用正确的ANSI-92 JOIN语法-在ON子句中指定了JOIN标准:

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. 如果没有JOIN条件,MySQL将返回笛卡尔乘积,然后将WHERE子句应用于这些结果。 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. 另外, INNER关键字是可选的。

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. 使用ON定义统计信息如何连接到成员,并使用WHERE限制成员表的结果。

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. 由于它是一个INNER JOIN,因此您也可以将其翻转(从统计数据中选择,加入成员),但是考虑到您正在寻找某个成员,这可能更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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