Mysql查询distinct + multiple

时间:2012-11-15 03:24:13

标签: mysql sql join

我想做这个查询:

SELECT * 
   FROM user k
   INNER JOIN (
      SELECT id, tagName, b.guid, name, owner, publicKey
         FROM noteTags a
         INNER JOIN (
            SELECT * 
            FROM note
            ORDER BY guid
            LIMIT 0 , 12
         )b ON a.guid = b.guid ORDER BY b.id DESC
   )l ON k.owner = l.owner

但我想让它返回DISTINCT b.guids。

表格的结构:

note
|
|=id
|=name
|=guid
|=owner
|=publicKey

noteTags
|
|=guid
|=tagName

user
|
|=owner
|=username
|=auth

基本上我想选择所有数据(对更深的内连接有限制)并返回DISTINCT guids

谢谢!

2 个答案:

答案 0 :(得分:0)

这是我的初步答案,

SELECT  *
FROM    note a
        INNER JOIN user b
            ON a.owner = b.owner
        INNER JOIN notetags c
            ON a.guid = b.guid
        INNER JOIN
        (
            SELECT guid, MAX(tagName) maxTag
            FROM notetags
            GROUP BY guid
        ) d ON c.guid = d.guid AND
                c.tagName = d.maxTag

答案 1 :(得分:0)

怎么样:

SELECT *
   来自用户k
   内部联合(
      SELECT id,tagName,b.guid,name,owner,publicKey
         来自noteTags a          内部联合(
            选择id,name,MIN(guid)作为guid,owner,publicKey
            来自备注
            GROUP BY guid
            限制0,12          )b ON a.guid = b.guid ORDER BY b.id DESC
   )l ON k.owner = l.owner