3表: Candidate
Id是该表的主键列。该表的每一行都包含关于候选对象的id和名称的信息。
表: Vote
Id是自动递增的主键。candidateId是id来自Candidate表的外键。该表的每一行决定了在选举中获得第i张选票的候选人。
问题:编写一个SQL查询来报告获胜候选人的名字(即获得最多选票的候选人)。生成测试用例以确保 只有一个候选人赢得选举。
结果格式:
输入: 输出:候选人B有2票。候选人C、D、E各有1票。
import java.sql.*;
public class test3 {
// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String url = "jdbc:mysql://localhost:3306/student_course";
// 数据库的用户名与密码,需要根据自己的设置
static final String user = "root";
static final String password = "123456";
public static void main(String[] args) {
Connection con = null;
Statement sta = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 连接数据库
con = DriverManager.getConnection(url,user,password);
sta=con.createStatement();
String s3 = "select name from student_course.candidate join student_course.vote " +
"on candidate.id = vote.candidateId group by name order by count(name) Desc limit 1;";
//按名字出现的次数降序取第一个
ResultSet rs3 = sta.executeQuery(s3);
if(rs3.next()) {
System.out.println("name");
System.out.println(rs3.getString("name"));
}
// 完成后关闭
sta.close();
con.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(sta!=null) sta.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(con!=null) con.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}