Junior — Middle
How to determine the number of records in a table that have no links to records in another table?
sobes.tech AI
Answer from AI
To determine the number of records in one table that have no relations with records in another table, a SQL query with a LEFT JOIN operator and a NULL check in the related table is usually used. For example, if there is a table A and a related table B, the query would look like this:
SELECT COUNT(*)
FROM A
LEFT JOIN B ON A.id = B.a_id
WHERE B.a_id IS NULL;
This query selects all records from A, tries to find corresponding records in B, and then counts only those that have no related record (i.e., B.a_id is NULL).
In Java, to execute such a query, you can use JDBC or ORM (e.g., JPA/Hibernate). An example with JDBC:
String sql = "SELECT COUNT(*) FROM A LEFT JOIN B ON A.id = B.a_id WHERE B.a_id IS NULL";
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
int count = rs.getInt(1);
System.out.println("Number of records without relations: " + count);
}
}
Thus, using an SQL query and Java, you can obtain the required number of records without relations.