Using different attributes
If you want in the results, one line at a time id
, you can use GROUP BY id
. But then it is not recommended to use other columns in the list SELECT
(even if MySQL allows it) - it depends if you have the parameter ANSI
On
or Off
). It is advisable to use other columns with aggregate functions, such as MIN()
, MAX()
, COUNT()
, etc. There is also an aggregate function in MySQL GROUP_CONCAT()
that will collect all values from a column for a group:
SELECT
id
, COUNT(*) AS number_of_rows_with_same_id
, MIN(col1) AS min_col1
, MAX(col1) AS max_col1
--
, GROUP_CONCAT(col1) AS gc_col1
, GROUP_CONCAT(col2) AS gc_col2
--
, GROUP_CONCAT(col16) AS gc_col16
FROM
abc
GROUP BY
id ;
Request:
SELECT *
FROM abc
GROUP BY id ;
invalid SQL (up to 92) because you have non-aggregated results in the list SELECT
and are valid in SQL (2003+). However, it is not valid here because the other columns are functionally independent of the grouping column ( id
). MySQL, unfortunately, allows such queries and does not test for functional dependencies.
So, you never know which string (from the number with the same id
) will be returned, or even if - horror! - you get results from different rows (with the same id). As @Andriy points out, the implications are that values for columns other than id
will be chosen arbitrarily. If you want predictable results, just don't use this technique.
Example solution: if you only want one row from each id
and you have a datetime or timestamp (or whatever) column that you can use to order, you can do this:
SELECT t.*
FROM abc AS t
JOIN
( SELECT id
, MIN(some_column) AS m -- or MAX()
FROM abc
GROUP BY id
) AS g
ON g.id = t.id
AND g.m = t.some_column ;
This will work as long as the combination is (id, some_column)
unique.
source to share