简体   繁体   中英

SQL MAX in conjunction with WHERE clause

I need to find the largest value from one particular column in a mysql table where the value of another column is equivalent to something. But, with the query that I'm using, I keep on getting a message that displays and SQL error. My query is aS follows:

SELECT MAX(message_id) AS top_message HAVING(child_id) = '".$message_id[$i]."'

Any suggestions?

您还缺少表名:

SELECT MAX(message_id) AS top_message FROM tablename WHERE child_id = '".$message_id[$i]."'

You should use WHERE instead of HAVING Clause:

SELECT MAX(message_id) AS top_message 
FROM tablename 
WHERE child_id = '".$message_id[$i]."'

Use only HAVING clause when you have an aggregated conditon.

You need a from clause and a where clause. The having clause is used for group filters. You don't have a group by clause, so there is no reason to write a having clause. If the table where you want to select from is called 'MyTable', then your query is as follows:

SELECT MAX(message_id) AS top_message
FROM MyTable
WHERE child_id = '".$message_id[$i]."'

Note, that the paranthesis around child_id is not needed. Please read SQL and MySQL tutorials for more information, your life will be much easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM