我有一个mysql数据库,我每天早上从oracle db导入数据。该表约有3000万条记录。这大约需要5-6个小时。 在晚上,我复制了表格,以便我可以从显示包含表格内容的网格的网站上访问它。
表格如下所示
id userID fieldID date1 date2
1 1 1 2014 2014
2 1 1 2014 2016
3 1 1 2013 2017
4 1 2 2014 2016
5 2 3 2014 2016
基本上在用户输入用户ID的网站上,我必须显示每个具有最新日期1的fieldID的记录,然后显示最新的日期2 所以userID = 1的输出应为:
id userID fieldID date1 date2
2 1 1 2014 2016
4 1 2 2014 2016
我目前使用的查询是:
SELECT id,UserID,fieldID,date1,date2 FROM mytable WHERE id =
( SELECT id from mytable AS lookup
WHERE lookup.fieldID = mytable.fieldID
ORDER BY date1 DESC, date2 DESC
LIMIT 1 ) AND UserID=1
这可行,但查询服务器并加载页面需要很长时间,而如果我选择特定用户ID的所有内容,则需要一秒钟来获取大约2000行
我想知道你是否可以建议一个更好的查询或者可能是一个解决方法,而不是复制表,我创建了一个只有我需要的记录(网站不在晚上使用)。
感谢
答案 0 :(得分:0)
SELECT
id,
UserID,
fieldID,
(SELECT MAX(date1) FROM mytable WHERE fieldID=mt.fieldID) As DateOne,
(SELECT MAX(date2) FROM mytable WHERE fieldID=mt.fieldID) As DateTwo,
FROM mytable mt
WHERE UserID=1
答案 1 :(得分:0)
如下:
SELECT id, mytable.UserID, mytable.fieldID, A.date1, B.date2
FROM mytable AS outer,
(
SELECT MAX(date1) AS date1
FROM mytable AS innerone
WHERE innerone.id=outer.id
WHERE innerone.UserID=outer.UserID
AND innerone.fieldID=outer.fieldID
GROUP BY innerone.id,
innerone.UserID,
innerone.fieldID
) AS A,
(
SELECT MAX(date2) AS date2
FROM mytable AS innertwo
WHERE innertwo.id=outer.id
WHERE innertwo.UserID=outer.UserID
AND innertwo.fieldID=outer.fieldID
GROUP BY innertwo.id,
innertwo.UserID,
innertwo.fieldID
) AS B
WHERE UserID=1