开发者

optimizing a complex query in mysql

I have two questions here but i am asking them at once as i think they are inter-related.

I am working with a complex query (Multiple joins + sub queries) and the table is pretty huge as well (around 2,00,000 records in this table).

A part of this query (a LEFT JOIN) is required to find a record which has a second lowest value in a cetain column among all the records associated with the primary key of the first table. For now I have isolated this part and thinking on the lines of -

SELECT id FROM tbl ORDER BY `myvalue` ASC LIMIT 1,1;

But there is a case where, if there is only 1 record in the table, it must return that record instead of NULL. So my first question is how do write a query for this ?

Secondly, considering the size of the table and the time its already taking to run even after creating indexes, I understand that adding any more complexity to it in order to achieve the above part might affect the querying time dramatically.

I cannot decompose joins because I need to get some of the columns for the ORDER BY clause (the application has an option to sort the result by these columns, the above 开发者_StackOverflowcolumn "myvalue" being one of them)

What would be the way(s) to approach this problem ?

Thanks


Something like this might work

COALESCE(
  (SELECT id FROM tbl ORDER BY `myvalue` ASC LIMIT 1,1), 
  (SELECT id FROM tbl ORDER BY `myvalue` ASC LIMIT 0,1))

It selects the first non null value from the list provided.

As for the complexity of the query, post the whole thing so we can take a look at it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜