2013-12-15 27 views
0

我有3個表格,一個存儲圖片和一個存儲圖片的投票(picturespicture_votes)。最後一個表格是categories,它存儲了圖片可以屬於的不同類別。從第三張表中的每一行中獲取另一張表的頂部3

這裏是表(不相關的列省略);

- Table `pictures` 
picture_id INT 
category_id INT 

- Table `picture_votes` 
vote  TINYINT 
picture_id INT 

最後

- Table `categories` 
category_id INT 

我想要做什麼是選擇的3件最投票圖片每個類別。

我真的迷路了,不知道如何最有效地做到這一點..

回答

0

我想出了這一點;

(SELECT p.* 
FROM 
    pictures p 
LEFT JOIN 
    picture_votes pv 
    ON pv.picture_id = p.picture_id 
WHERE p.category_id = n 
GROUP BY p.picture_id 
ORDER BY SUM(pv.vote) DESC 
LIMIT 3) 
UNION 
(SELECT ...) 
UNION 
(SELECT ...) 
--And so on for every category_id (there are 9) 

這看起來像veeeery不好的解決方案,查詢花了太長時間。

2

如果你能在每個類別一行接受它們作爲一個逗號分隔的列表:

select pv.category_id, 
     substring_index(group_concat(pv.picture_id order by numvotes desc), ',', 3) as Top3 
from (select p.category_id, p.picture_id, count(*) as numvotes 
     from picture_votes pv join    
      pictures p    
      on p.picture_id = pv.picture_id 
     group by p.category_id, p.picture_id 
    ) pv 
group by pv.category_id; 
0

sqlFiddle

SELECT category_id,picture_id,ranking FROM 
(
select c.category_id,(select p.picture_id 
        from pictures p, picture_votes pv 
        where p.picture_id = pv.picture_id 
        and p.category_id = c.category_id 
        group by p.picture_id 
        order by sum(pv.vote) desc 
        limit 0,1)as picture_id,1 as ranking 
    from categories c 

union 

select c.category_id,(select p.picture_id 
        from pictures p, picture_votes pv 
        where p.picture_id = pv.picture_id 
        and p.category_id = c.category_id 
        group by p.picture_id 
        order by sum(pv.vote) desc 
        limit 1,1)as picture_id,2 as ranking 
    from categories c 

union 
select c.category_id,(select p.picture_id 
        from pictures p, picture_votes pv 
        where p.picture_id = pv.picture_id 
        and p.category_id = c.category_id 
        group by p.picture_id 
        order by sum(pv.vote) desc 
        limit 2,1)as picture_id,3 as ranking 
    from categories c 
)result 
WHERE picture_id is not null 
order by category_id asc,ranking asc 

或本sqlFiddle

SELECT picture_id,category_id,sumvotes,voteOrder 
FROM 
    (SELECT picture_id,category_id,sumvotes, 
     IF(@prevCat <> category_id,@voteOrder:=1,@voteOrder:[email protected]+1) 
     as voteOrder, 
     @prevCat:=category_id 
    FROM(SELECT p.picture_id, 
       p.category_id, 
       SUM(pv.vote) as sumvotes 
      FROM pictures p 
      JOIN picture_votes pv 
      ON p.picture_id = pv.picture_id 
      GROUP BY p.picture_id, 
        p.category_id 
      ORDER BY p.category_id, sumvotes DESC 
     )as ppv, 
    (SELECT @prevCat:=0,@voteOrder:=0)pc 
    )finalTable 
WHERE voteOrder BETWEEN 1 AND 3 
ORDER BY category_id ASC, voteOrder ASC 
相關問題