Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL row subquery comparison issue

I have a small mysql table (MySQL version 5.6.23) :

+-----------+-----------------+------+-----+---------+----------------+
| Field     | Type            | Null | Key | Default | Extra          |
+-----------+-----------------+------+-----+---------+----------------+
| id        | int(6) unsigned | NO   | PRI | NULL    | auto_increment |
| dividends | float(8,6)      | YES  |     | NULL    |                |
+-----------+-----------------+------+-----+---------+----------------+

My where clause follows the row-subqueries syntax.
If I do:

SELECT id, dividends FROM test  
  where  (id,dividends) >= (660,0.5);

or

SELECT id, dividends FROM test 
  where  (id,dividends) >= (660,CAST(0.5 AS DECIMAL(8,6)));

I get this result:

+-----+-----------+
| id  | dividends |
+-----+-----------+
| 660 |  0.500000 |
| 661 |  0.470000 |
| 662 |  0.470000 |
| 663 |  0.470000 |
| 664 |  2.580000 |
| 665 |  2.581000 |
...

It seems to me that dividends >= 0.5 is not taken into consideration. Why?

like image 796
Bruckwald Avatar asked Mar 23 '15 09:03

Bruckwald


1 Answers

You're using row constructors. MySQL treats them exactly like rows of a table. Thus WHERE (id,dividends) >= (660,0.5) effectively does the same as:

  1. ORDER BY id,dividends;

  2. Find the point at which (660,0.5) would sit within that ordering;

  3. Filter for only those records that are equal to or greater than that point in the ordering.

Consequently, it is the same as WHERE (id=660 AND dividends>=0.5) OR id>660.

It appears as though the logic you really wish to express is WHERE id>=660 AND dividends>=0.5.

like image 141
eggyal Avatar answered Sep 21 '22 19:09

eggyal