选择具有最高值的行和连接

时间:2014-04-30 11:50:56

标签: mysql sql row highest

何我只能获取cvID值最高的行?

当前代码

SELECT 
  CollectionVersionBlocks.cID,
  CollectionVersionBlocks.cbDisplayOrder,
  CollectionVersionBlocks.cvID,
  btContentLocal.bID,
  btContentLocal.content 
FROM
  CollectionVersionBlocks 
  INNER JOIN btContentLocal 
    ON CollectionVersionBlocks.bID = btContentLocal.bID 
WHERE (CollectionVersionBlocks.cID = 259)
  AND CollectionVersionBlocks.isOriginal = 1 
  AND CollectionVersionBlocks.arHandle = 'main' 
  AND btContentLocal.content != '' 

我想在底部获取行(cvID值为10)。

这是一个更大结果集的测试语句 -

我最终需要一组来自perset cIDs的结果(CollectionVersionBlocks.cID = 259或CollectionVersionBlocks.cID = 260 ......高达800)

picture of result

更新截图

1)结果太少了 2)未分组的结果

result2

enter image description here

2 个答案:

答案 0 :(得分:2)

要获得每组最高行(从您的问题我假设cID作为单个组),您可以通过在所需列的最大值上使用自联接来实现此目的在第三次加入中使用附加条件,即ON(c.cID=cc.cID AND c.cvID=cc.cvID)

SELECT 
  c.cID,
  c.cbDisplayOrder,
  c.cvID,
  b.bID,
  b.content 
FROM
  CollectionVersionBlocks  c
  INNER JOIN btContentLocal b
    ON (c.bID = b.bID)
  INNER JOIN 
  (SELECT cID, MAX(cvID) cvID FROM CollectionVersionBlocks GROUP BY cID) cc
  ON(c.cID=cc.cID AND c.cvID=cc.cvID)
WHERE (c.cID = 259)
  AND c.isOriginal = 1 
  AND c.arHandle = 'main' 
  AND b.content != ''

对于多个群组,您只需使用WHERE c.cID IN(259,....800)

即可

答案 1 :(得分:0)

尝试以下查询:

SELECT CollectionVersionBlocks.cID,CollectionVersionBlocks.cbDisplayOrder,        CollectionVersionBlocks.cvID ,  btContentLocal.bID , btContentLocal.content 
FROM CollectionVersionBlocks
INNER JOIN btContentLocal
ON CollectionVersionBlocks.bID=btContentLocal.bID 
WHERE (CollectionVersionBlocks.cID = 259) 
AND CollectionVersionBlocks.isOriginal=1 AND CollectionVersionBlocks.arHandle ='main'            AND           btContentLocal.content !='' and CollectionVersionBlocks.cID in
(

    SELECT Max(CollectionVersionBlocks.cID)
    FROM CollectionVersionBlocks
    INNER JOIN btContentLocal
    ON CollectionVersionBlocks.bID=btContentLocal.bID 
    WHERE (CollectionVersionBlocks.cID = 259) 
    AND CollectionVersionBlocks.isOriginal=1 AND CollectionVersionBlocks.arHandle   ='main' AND btContentLocal.content !='' )