我有桌子,
id | OpenDate | CloseDate
------------------------------------------------
1 | 2013-01-16 07:30:48 | 2013-01-16 10:49:48
2 | 2013-01-16 08:30:00 | NULL
我需要得到如下结合的结果
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
我使用UNION来获得输出(我们可以在没有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
我正在获得所需的输出,但现在在性能方面 - >我在我的桌子上有4000条记录,通过UNION进行组合并提供大约8000条记录,加载网站的速度非常慢(超过13秒)。如何优化此查询以固定输出?
我也在子查询中尝试了LIMIT
,如果我在子查询中使用LIMIT
,则分页偏移无法正常工作。请帮我解决这个问题。
更新
EXPLAIN结果
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
答案 0 :(得分:1)
我会做以下事情:
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);