I have a table that looks like this:
+------+--------+----------+------+--------+-------+------+------------+ | id | code | category | mq | weight | weave | show | min(price) | +------+--------+----------+------+--------+-------+------+------------+ | 1 | DT450R | carbon | 1 | 450 | plain | 1 | 90 | | 2 | DT450R | carbon | 2 | 450 | plain | 1 | 40 | | 3 | DT450R | carbon | 5 | 450 | plain | 1 | 75 | | 7 | PP120Q | carbon | 3 | 120 | twill | 1 | 28 | | 8 | PP120Q | carbon | 7 | 120 | twill | 1 | 65 | | 9 | PP120Q | carbon | 9 | 120 | twill | 1 | 49 | | 4 | ZX300R | carbon | 1 | 300 | plain | 0 | 12 | | 5 | ZX300R | carbon | 15 | 300 | plain | 1 | 128 | | 6 | ZX300R | carbon | 30 | 300 | plain | 1 | 92 | +------+--------+----------+------+--------+-------+------+------------+
I've created a sqlfiddle here.
I want min price from table in each code. I tried using the following query:
select id, code, category, mq, weight, weave, price, `show`, min(price) as total
from product group by code;
Why is the group by getting the wrong result? It's returning id = 1 instead of id =2.
Incorrect output:
+------+--------+----------+------+--------+-------+------+------------+ | id | code | category | mq | weight | weave | show | min(price) | +------+--------+----------+------+--------+-------+------+------------+ | 1 | DT450R | carbon | 1 | 450 | plain | 1 | 40 | | 7 | PP120Q | carbon | 3 | 120 | twill | 1 | 28 | | 4 | ZX300R | carbon | 1 | 300 | plain | 0 | 12 | +------+--------+----------+------+--------+-------+------+------------+
Expected output:
+------+--------+----------+------+--------+-------+------+------------+ | id | code | category | mq | weight | weave | show | min(price) | +------+--------+----------+------+--------+-------+------+------------+ | 2 | DT450R | carbon | 2 | 450 | plain | 1 | 40 | | 4 | ZX300R | carbon | 1 | 300 | plain | 0 | 12 | | 7 | PP120Q | carbon | 3 | 120 | twill | 1 | 28 | +------+--------+----------+------+--------+-------+------+------------+