I cannot find answer to my issue, though I've looked at other similar queries. My exercise was to join two tables in Mysql (tables USERS and POSTS) and when posts are added by a user, check if the actual count of users that posted at least twice changes.
The test stops when it reaches line of printing posts_number, firstname and lastname, saying that column couldn't be found. (I tried switching the order, but the same error pops up). Anyone having correction ideas?
Here is my java code:
@Test
public void testSelectUsersAndPosts () throws SQLException {
//given
DbManager dbManager = DbManager.getInstance();
String countQuery = "SELECT COUNT(*) FROM POSTSBYNUMBER";
Statement statement = dbManager.getConnection().createStatement();
ResultSet rs = statement.executeQuery(countQuery);
int count = 0;
while (rs.next()) {
count = rs.getInt("COUNT(*)");
}
String sql = "INSERT INTO POSTS(USER_ID, BODY) VALUES ('8', 'ha')";
statement.executeUpdate(sql);
sql = "INSERT INTO POSTS(USER_ID, BODY) VALUES ('8', 'yes')";
statement.executeUpdate(sql);
//when
String sqlQuery = "SELECT COUNT(*) FROM POSTSBYNUMBER";
statement = dbManager.getConnection().createStatement();
rs = statement.executeQuery(sqlQuery);
//then
int counter = 0;
while(rs.next()) {
System.out.println(rs.getInt("POSTS_NUMBER") + ", " + //HERE MY ERROR POPS UP
rs.getString("FIRSTNAME") + ", " +
rs.getString("LASTNAME"));
counter++;
}
int expected = count + 1 ;
Assert.assertEquals(expected, counter);
rs.close();
statement.close();
}
Table created using CREATE VIEW:
CREATE VIEW POSTSBYNUMBER AS
SELECT u.FIRSTNAME, u.LASTNAME, COUNT(*) AS POSTS_NUMBER
FROM USERS u JOIN
POSTS p
ON u.ID = p.USER_ID
GROUP BY u.FIRSTNAME, u.LASTNAME
HAVING COUNT(*) >= 2;