如何获取具有列的最大值的行

时间:2015-02-21 07:43:25

标签: mysql

这个MySQL查询返回3行,但我想只选择total_votes = max(total_votes);的那一行,请告诉我该怎么办?

SELECT 
      assembly, 
      seat_code, 
      CONCAT(first_name, ' ', last_name), 
      total_votes, 
      party_id      
FROM (polling JOIN seat USING (seat_id) JOIN candidate USING (candidate_id))
WHERE seat_id = 1;

2 个答案:

答案 0 :(得分:2)

替换您的查询
SELECT 
      assembly, 
      seat_code, 
      CONCAT(first_name,' ',last_name), 
      total_votes, 
      party_id      
FROM (polling JOIN seat USING (seat_id) JOIN candidate USING (candidate_id))
WHERE seat_id=1;

SELECT 
      assembly, 
      seat_code, 
      CONCAT(first_name,' ',last_name), 
      total_votes, 
      party_id      
FROM (polling JOIN seat USING (seat_id) JOIN candidate USING (candidate_id))
WHERE seat_id=1 AND total_votes=(SELECT MAX(total_votes) FROM <table name>);

答案 1 :(得分:0)

您可以使用MAX聚合:

SELECT 
      assembly, 
      seat_code, 
      CONCAT(first_name,' ',last_name)name, 
      MAX(total_votes)total_votes, 
      party_id      
FROM polling JOIN seat USING (seat_id) JOIN candidate USING (candidate_id)
WHERE seat_id=1;
  

注意:无需在JOIN部分放置括号。