基本上我在一个表中有一个SEO关键字列表,其排名包括在另一个表中输入的日期。
[keywordID(PKID)] [keyword]
----------------------------
1 SEO
2 Vancouver Homes
[rankingID(PKID)] [keywordID(FKID)] [ranking] [rankingDate(timestamp)]
----------------------------------------------------------------------
1 1 3 Jan 01, 2010
2 1 5 Jan 02, 2010
3 1 8 Jan 03,2010
4 2 4 Jan 01, 2010
以下是我想要的结果。我希望根据最新排名日期对关键字进行最新排名而不重复。
对于上面的数据,它应该返回:
[keywordID] [rankingID] [ranking] [rankingDate]
-----------------------------------------------
SEO 1 3 8 Jan 03, 2010
Vancouver Homes 4 2 4 Jan 01, 2010
选择关键字的最新排名是什么声明?现在我让它返回关键字ID的重复行。
请询问我目前的sql语句是否需要更多信息。
SELECT *
from keywords,
keywordRankings
WHERE keywords.keywordID = keywordRankings.keywordID;
我现在的解决方案对我有用......
SELECT s1.keywordID, keyword, rankingDate, ranking
FROM keywords s1, keywordRankings
WHERE keywordRankingRecord = (
SELECT MAX( s2.keywordRankingRecord )
FROM keywordRankings s2
WHERE s1.keywordID = s2.keywordID )
答案 0 :(得分:1)
here解释了在群体中找到最大值的基本思想。
SELECT k.keyword,
r1.*
FROM keyword AS k
LEFT JOIN keywordRanking AS r1
ON k.keywordid = r1.keywordid
LEFT JOIN keywordRanking AS r2
ON k.keywordid = r2.keywordid
AND r1.rankingdate < r2.rankingdate
WHERE r2.ranking IS NULL
产量
+-----------------+-----------+-----------+---------+---------------------+
| keyword | keywordID | rankingID | ranking | rankingDate |
+-----------------+-----------+-----------+---------+---------------------+
| SEO | 1 | 3 | 8 | 2010-01-03 00:00:00 |
| Vancouver Homes | 2 | 4 | 4 | 2010-01-01 00:00:00 |
+-----------------+-----------+-----------+---------+---------------------+