I have following two query both are same but differs only in structure.
First query:
SELECT DISTINCT
u.username, r.value, u.amount AS `amount`
FROM
Daily_Balance_Updates u
INNER JOIN
Role r ON u.role_id = r.id
WHERE
u.updated_at = (SELECT MAX(inner_u.updated_at)
FROM Daily_Balance_Updates AS inner_u
WHERE inner_u.username = u.username
&& amount > 0
&& UNIX_TIMESTAMP( inner_u.updated_at ) < UNIX_TIMESTAMP( '2013-1-3 23:59:59' )
)
ORDER BY
r.value, UNIX_TIMESTAMP( u.updated_at ) DESC
Works fine in Phpmyadmin
Second query
And same query when I use in Java I declare as follow:
query="SELECT DISTINCT u.username, r.value, u.amount AS `amount' FROM Daily_Balance_Updates u INNER JOIN Role r ON u.role_id = r.id WHERE u.updated_at = ("
+ "SELECT MAX(inner_u.updated_at) FROM Daily_Balance_Updates AS inner_u WHERE inner_u.username = u.username && amount > 0 && UNIX_TIMESTAMP( inner_u.updated_at ) < UNIX_TIMESTAMP('" +date+" 23:59:59' )) ORDER BY r.value DESC,UNIX_TIMESTAMP( u.updated_at )"
but when I execute it it gives error in both phpmyadmin and java
ERROR
Unknown table ‘u’ in field list
My log:
12:23:17,963 INFO [STDOUT] 2013-01-07 12:23:17,962 ERROR
com.walletplus.report.dao.ReportDaoMysql - Thread #98 -
StatementCallback; bad SQL grammar
[SELECT DISTINCT u.username, r.value, u.amount AS `amount' FROM
Daily_Balance_Updates u INNER JOIN Role r ON u.role_id = r.id
WHERE u.updated_at = (SELECT MAX(inner_u.updated_at) FROM
Daily_Balance_Updates AS inner_u WHERE inner_u.username = u.username
&& amount > 0 && UNIX_TIMESTAMP( inner_u.updated_at ) <
UNIX_TIMESTAMP('2013-01-01 23:59:59' )) ORDER BY r.value DESC];
nested exception is java.sql.SQLException: Unknown table 'u' in field list
Question:
What is wrong with query? It seems all right.
You have two differences in those two queries
I guess, that’s the reason, why
FROM Daily_Balance_Updates uisn’t recognized, and you get the misleading error message.order by ... desc, ...vsorder by ..., ... descAnother point, if you have a
user_idin addition tousername, comparing theuser_ids in the where clause would be faster.