SQL中count(1)、count(*) 与 count(列名)的区别详细解释

  import java.sql.Connection;

  import java.sql.DriverManager;

  import java.sql.Statement;

  import java.sql.ResultSet;

  import java.sql.SQLException;

  public class CountExample {

  private static final String JDBC_URL = "jdbc:mysql://localhost:3306/yourdatabase";

  private static final String JDBC_USER = "yourusername";

  private static final String JDBC_PASSWORD = "yourpassword";

  public static void main(String[] args) {

  try (Connection conn = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);

  Statement stmt = conn.createStatement()) {

  // 使用 COUNT(1)

  String count1SQL = "SELECT COUNT(1) AS total FROM employees";

  ResultSet rs1 = stmt.executeQuery(count1SQL);

  if (rs1.next()) {

  int total1 = rs1.getInt("total");

  System.out.println("Total rows (COUNT(1)): " + total1);

  }

  // 使用 COUNT(*)

  String countAllSQL = "SELECT COUNT(*) AS total FROM employees";

  ResultSet rsAll = stmt.executeQuery(countAllSQL);

  if (rsAll.next()) {

  int totalAll = rsAll.getInt("total");

  System.out.println("Total rows (COUNT(*)): " + totalAll);

  }

  // 使用 COUNT(column)

  String countColumnSQL = "SELECT COUNT(department_id) AS total FROM employees";

  ResultSet rsColumn = stmt.executeQuery(countColumnSQL);

  if (rsColumn.next()) {

  int totalColumn = rsColumn.getInt("total");

  System.out.println("Total rows (COUNT(department_id)): " + totalColumn);

  }

  } catch (SQLException e) {

  e.printStackTrace();

  }

  }

  }