MySQL查询加速

时间:2012-05-03 11:04:58

标签: mysql database performance left-join

我的查询速度有问题 - 此刻它的运行时间大约是16秒,我需要加快速度!

我的表格方案如下:

用户:

  • id(int 10,主键)
  • 用户名(varchar 100)
  • 密码(varchar 100)

Users_meta:

  • id(int 10,主键)
  • user(int 10)
  • meta(varchar 100)
  • value(longtext)

我需要将用户元表中各行的数据(例如名字,姓氏等)作为列返回。此查询完成了这项工作,但运行速度太慢了:

SELECT
Users.id as id,
Users.username as username,
firstName.value as metaFirstName,
lastName.value as metaLastName,
userLevel.value as metaUsername,
employer.value as metaEmployer,
gto.value as metaGTO
FROM Users
LEFT JOIN (Users_meta as firstName) ON (firstName.user = Users.id AND firstName.meta = 'first_name')
LEFT JOIN (Users_meta as lastName) ON (lastName.user = Users.id AND lastName.meta = 'last_name')
LEFT JOIN (Users_meta as userLevel) ON (userLevel.user = Users.id AND userLevel.meta = 'user_level')
LEFT JOIN (Users_meta as employer) ON (employer.user = Users.id AND employer.meta = 'employer')
LEFT JOIN (Users_meta as gto) ON (gto.user = Users.id AND gto.meta = 'gto')

我还需要能够在查询中添加WHERE和ORDER BY子句。

感谢您的帮助。 :)

2 个答案:

答案 0 :(得分:2)

我不知道这是否更快。但也许是这样的:

SELECT
    Users.id as id,
    Users.username as username,
    MAX(CASE WHEN Users_meta.meta = 'first_name' THEN Users_meta.value ELSE NULL END) AS metaFirstName,
    MAX(CASE WHEN Users_meta.meta = 'last_name' THEN Users_meta.value ELSE NULL END) AS metaLastName,
    MAX(CASE WHEN Users_meta.meta = 'user_level' THEN Users_meta.value ELSE NULL END) AS metaUsername,
    MAX(CASE WHEN Users_meta.meta = 'employer' THEN Users_meta.value ELSE NULL END) AS metaEmployer,
    MAX(CASE WHEN Users_meta.meta = 'gto' THEN Users_meta.value ELSE NULL END) AS metaGTO
FROM
    Users
    LEFT JOIN Users_meta
        ON Users_meta.user = Users.id
GROUP BY
    Users.ID,
    Users.username

答案 1 :(得分:1)

我首先在表meta:(meta, user, value)上添加一个复合索引。或(user, meta, value)。如果您的查询中有其他WHERE条件,这些肯定会有所帮助。

查询现在已经使用(几乎)表Users_meta中的所有数据,因此可能无法使用这些索引。

longtext数据类型是另一个问题。你确定你需要那么宽的柱子吗?