开发者

MySql query: select a list of tag names and for each tag get the most recently tagged albums information

开发者 https://www.devze.com 2023-03-29 20:18 出处:网络
I am not quite sure how to write this query of it it can be done in one query. Here is the case: I need to select a list of tag names and for each tag get the most recently tagged albums informatio

I am not quite sure how to write this query of it it can be done in one query. Here is the case:

I need to select a list of tag names and for each tag get the most recently tagged albums information. Meaning that if a user creates an album called "Pamela Anderson" and tags that album as "Blondes" then that album is now the most recently tagged album for Blondes. There might be 100 albums tagged as "Blondes" but only the most recent one's data should be selected, as determined by the objectTagCreateDate.

The expected data would look like this:

    tagId, tagName,   objectTagCreateDate, albumName,       albumPath
   --------------------------------------------------------------------
    1,     Blondes,   2011-08-23,          Pamela Anderson,   7345
    2,     Celebs,    2011-08-20,          Kate Winslet,    2, 5567
    3,     Musicians, 2011-08-22,     开发者_JAVA百科     Alicia Keys,       6678

etc

The tables look like this:

Tag
 - tagId
 - tagName

ObjectTag
 - objectType
 - objectId
 - tagId
 - objectTagCreateDate

Album
 - albumId
 - albumName
 - albumPath

The join happens on:

tag.tagId = objectTag.tagId AND objectTag.objectType = 3 and objectTag.objectId = album.albumId

Can this be done in one query and if so how?


SELECT t.tagId, t.tagName, o.objectTagCreateDate, a.albumName, a.albumPath
FROM ObjectTag AS o
INNER JOIN (
            SELECT tagId, MAX(objectTagCreateDate) As MaxDate
            FROM ObjectTag
            WHERE ObjectTag.objectType = 3
            GROUP BY tagId
            ) AS t1
ON t1.tagId = o.tagId AND t1.MaxDate = o.objectTagCreateDate
INNER JOIN Tag AS t ON t1.tagId = t.tagId
INNER JOIN Album AS a ON o.objectID = a.albumId

The inner select gets the MaxDate per tagId and joins with ObjectTag to get the corresponding o.objectID. The rest is just simple joins.


Something like this should do it but I haven´t tested it myself;

SELECT T.tagId, T.tagName, MAX(OT.objectTagCreateDate) AS LatestObjectTagCreateDate, A.albumName, A.albumPath
FROM ObjectTag OT
JOIN Tag T ON (T.tagId = OT.tagId)
JOIN Album A ON (A.albumId = OT.objectId AND OT.objectType = 3)
GROUP BY T.tagId
ORDER BY T.tagId
0

精彩评论

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