0

如何优化这个查询 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);
        }
    }
4

2 回答 2

1

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

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

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

于 2013-10-09T13:54:31.513 回答
1

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

ALTER TABLE `rooms` ADD INDEX `owner` (`owner`)
于 2013-10-09T13:50:13.277 回答