How to get combined result in MySQL with query optimization?

筅森魡賤 提交于 2019-12-23 04:39:14

问题


I have table like,

id  | OpenDate             |  CloseDate
------------------------------------------------
1   | 2013-01-16 07:30:48  |  2013-01-16 10:49:48
2   | 2013-01-16 08:30:00  |  NULL

I needed to get combined result as below

 id | date                 |   type
 ---------------------------------
 1  | 2013-01-16 07:30:48  |  Open
 1  | 2013-01-16 10:49:48  |  Close
 2  | 2013-01-16 08:30:00  |  Open

I used UNION to get above output (can we achieve without UNION?)

SELECT id,date,type FROM(
   SELECT id,`OpenDate` as date, 'Open' as 'type' FROM my_table
  UNION ALL
   SELECT id,`CloseDate` as date, 'Close' as 'type' FROM my_table
                       )AS `tab` LIMIT 0,15

I am getting the desired output, but now in performance side--> i have 4000 records in my table and by doing UNION its combining and giving around 8000 records, which is making very slow to load the site(more than 13 sec). How can i optimize this query to fasten the output?

I tried LIMIT in sub-query also, pagination offset is not working properly as it should if i use LIMIT in sub-query. Please help me to resolve this.

Update

EXPLAIN result

id   select_type  table     type   key    key_len    ref     rows   Extra
1    PRIMARY     <derived2> ALL   NULL      NULL      NULL   8858    
2    DERIVED     orders     index OpenDate   4        NULL   4588   Using index
3    UNION       orders     index CloseDate  4        NULL   4588   Using index
NULL UNION RESULT<union2,3> ALL   NULL      NULL      NULL   NULL    

回答1:


I would do something like the following:

SELECT
  id,
  IF(act, t1.OpenDate, t1.CloseDate) as `date`,
  IF(act, 'Open', 'Close') as `type`
FROM my_table t1
JOIN (SELECT 1 as act UNION SELECT 0) as _
JOIN my_table t2 USING (id);


来源:https://stackoverflow.com/questions/14354828/how-to-get-combined-result-in-mysql-with-query-optimization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!