如何优化一个长查询mysql

时间:2013-10-09 13:44:21

标签: mysql

如何优化查询mysql:

SELECT * FROM rooms WHERE caption LIKE @query OR owner LIKE @query AND roomtype = 'private' ORDER BY users_now DESC LIMIT 50

这是我的代码:

internal ServerMessage SerializeSearchResults(string SearchQuery)
{
    DataTable Data = new DataTable();

    using (IQueryAdapter dbClient = PlusEnvironment.GetDatabaseManager().getQueryreactor())
    {
        if (SearchQuery.Length > 0)
        {
            if (SearchQuery.ToLower().StartsWith("owner:"))
            {
                dbClient.setQuery("SELECT * FROM rooms WHERE owner = @query AND roomtype = 'private' ORDER BY users_now DESC LIMIT 50");
                dbClient.addParameter("query", SearchQuery.Remove(0, 6));
            }
            else
            {
                dbClient.setQuery("SELECT * FROM rooms WHERE caption LIKE @query OR owner LIKE @query AND roomtype = 'private' ORDER BY users_now DESC LIMIT 50");
                dbClient.addParameter("query", "%" + SearchQuery + "%");
            }
            Data = dbClient.getTable();
        }
    }

    List<RoomData> Results = new List<RoomData>();

    if (Data != null)
    {
        foreach (DataRow Row in Data.Rows)
        {
            RoomData RData = PlusEnvironment.GetGame().GetRoomManager().FetchRoomData(Convert.ToUInt32(Row["id"]), Row);
            Results.Add(RData);
        }
    }

2 个答案:

答案 0 :(得分:1)

优化查询性能的最佳方法是将索引添加到where子句中更频繁使用的字段。例如,在MySQL中,您可以添加如下索引:

ALTER TABLE `rooms` ADD INDEX `owner` (`owner`)

答案 1 :(得分:1)

查询看起来并不复杂,因此您可以尝试按roomtype和users_now添加索引以加快SELECT。

CREATE INDEX index_name ON rooms (roomtype ASC, users_now DESC)    

还尝试限制查询中LIKE的使用,因为它严重影响了性能。