Lance
Lance

Reputation: 4820

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?

Upvotes: 0

Views: 87

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76414

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.

Upvotes: 0

hkf
hkf

Reputation: 4520

You are also missing a table name:

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

Upvotes: 4

John Woo
John Woo

Reputation: 263683

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.

Upvotes: 1

Related Questions