帮助MySql查询

时间:2011-08-23 08:52:29

标签: mysql

我不太确定如何编写此查询,可以在一个查询中完成。 情况就是这样:

我需要选择一个标签名称列表,并为每个标签获取最近标记的相册信息。意思是如果用户创建一个名为“Pamela Anderson”的专辑并将该专辑标记为“Blondes”,则该专辑现在是Blondes最近标记的专辑。 可能有100张专辑标记为“Blondes”,但只应选择最近的一张专辑,由objectTagCreateDate确定。

预期数据如下所示:

    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,          Alicia Keys,       6678

表格如下:

Tag
 - tagId
 - tagName

ObjectTag
 - objectType
 - objectId
 - tagId
 - objectTagCreateDate

Album
 - albumId
 - albumName
 - albumPath

联接发生在:

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

这可以在一个查询中完成,如果是这样的话怎么办? 感谢

2 个答案:

答案 0 :(得分:3)

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

内部选择获取每个tagId MaxDate并与ObjectTag结合以获得相应的o.objectID。其余的只是简单的连接。

答案 1 :(得分:0)

这样的事情应该这样做,但我自己没有测试过它;

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