简体   繁体   English

MySQL选择最大最大和值

[英]Mysql select max maximum sum values

I have a database which contains some picture data and a linking table. 我有一个包含一些图片数据和链接表的数据库。 The tables are build-up like this: 这些表是这样建立的:

---pictures---
picid    Lat  Lon
1        5    6
2        7    31
3        31   43
4        -3   35

---user2pictures---
picid   userid  vote
1       1      1
1       2      1
3       1     -1
3       2      1
4       2     -1

The table pictures contains a picture id and some data about the image, the table user2votes contains vote data from the images. 表格图片包含图片ID和有关图片的一些数据,表格user2votes包含图片中的投票数据。 Each user is able to vote on images, but they can only vote 1 time, so the vote will be either 1 (like) or -1 (dislike). 每个用户都可以对图像进行投票,但是他们只能投票1次,因此投票将为1(喜欢)或-1(不喜欢)。

I want to select everything from the pictures table from pictures which have the highest number of votes. 我想从具有最高投票数的图片的图片表中选择所有内容。 Pseudoquery which might explain better what I want: SELECT * FROM pictures WHERE (SELECT MAX(SUM(vote)) FROM user2pictures LIMIT 12 伪查询可能会更好地解释我想要什么: SELECT * FROM pictures WHERE (SELECT MAX(SUM(vote)) FROM user2pictures LIMIT 12

In this example picture 1 would return at the top, picture 3 would follow and picture 4 as the last one. 在此示例中,图片1将返回顶部,图片3将跟随其后,图片4作为最后一个。 I really don't know how to solve this, some help in the right direction would be very much appreciated! 我真的不知道如何解决这个问题,我们将不胜感激!

Thanks! 谢谢!

The answer is to JOIN the tables, SUM the votes, and ORDER high-to-low by the sum of the votes 答案是JOIN表, SUM票,和ORDER高到低的票数总和

SELECT pictures.*, SUM(user2pictures.vote) AS VoteTotal
FROM pictures
JOIN user2pictures ON pictures.picid = user2pictures.picid
GROUP BY pictures.picid
ORDER BY VoteTotal DESC
LIMIT 12

try this 尝试这个

   select p.`picid`, `Lat`, `Lon` from pictures p
   inner join user2pictures u2p
   on p.picid = u2p.picid
   group by u2p.picid
   order by sum(vote) desc
   limit 12

DEMO 演示

I'll assume that you also want to show the pictures with no votes. 我假设您也想不带票显示图片。 So, you can try this: 因此,您可以尝试以下操作:

select 
    p.picId, sum(v.vote) as votes
from 
    pictures as p
    left join user2pictures as v on p.picId = v.picId
group by
    p.picId
order by
    sum(v.vote) desc
limit 12;

The left join is what lets you show the pictures with no votes (the column votes will have the value 0 ) left join是让您显示没有投票的图片的方式(列votes的值为0

Hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM