Jump to content

SELECTING a row by its highest value


Phaelon

Recommended Posts

Hey all,

 

I want to select a row by its highest value for a specific field (a field called 'price').

 

I tried it with the following command, but it failed:

 

SELECT * FROM products WHERE MAX(price) AND gender = 'Mens' AND type = 'T-Shirt';

 

This is my table:

 

+-----------------+--------------+------+-----+-------------------+-------+
| Field           | Type         | Null | Key | Default           | Extra |
+-----------------+--------------+------+-----+-------------------+-------+
| number          | int(10)      | YES  |     | NULL              |       |
| gender          | varchar(6)   | YES  |     | NULL              |       |
| type            | varchar(25)  | YES  |     | NULL              |       |
| name            | varchar(50)  | YES  |     | NULL              |       |
| brand           | varchar(50)  | YES  |     | NULL              |       |
| colour          | varchar(50)  | YES  |     | NULL              |       |
| material        | varchar(50)  | YES  |     | NULL              |       |
| countryoforigin | varchar(50)  | YES  |     | NULL              |       |
| price           | decimal(6,2) | YES  |     | NULL              |       |
| cost            | decimal(6,2) | YES  |     | NULL              |       |
| adddate         | timestamp    | NO   |     | CURRENT_TIMESTAMP |       |
| weight          | int(5)       | YES  |     | NULL              |       |
| sizetype        | varchar(25)  | YES  |     | NULL              |       |
| sizexs          | varchar(2)   | YES  |     | NULL              |       |
| sizes           | varchar(2)   | YES  |     | NULL              |       |
| sizem           | varchar(2)   | YES  |     | NULL              |       |
| sizel           | varchar(2)   | YES  |     | NULL              |       |
| sizexl          | varchar(2)   | YES  |     | NULL              |       |
+-----------------+--------------+------+-----+-------------------+-------+

 

Does anyone know why it failed?

Link to comment
https://forums.phpfreaks.com/topic/288408-selecting-a-row-by-its-highest-value/
Share on other sites

You want to know where the price = MAX(price).

 

The WHERE clause is a boolean expression and selects those records where it evaluates to TRUE. Your WHERE clause (WHERE MAX(price)) always evaluates to true unless the max price is 0 and so selects all records

 

edit: Because you use an aggregation function (MAX, MIN, SUM, COUNT etc) without a group by, you only get a single row returned.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.