as I do to list for each city the oldest customers
As the structure of your table was not posted, I will suggest the following:
CREATE DATABASE `teste` DEFAULT CHARSET `utf8` DEFAULT COLLATE `utf8_unicode_ci`;
USE `teste`;
CREATE TABLE `clientes` (
`idCliente` int(11) NOT NULL AUTO_INCREMENT,
`nome` varchar(255) NOT NULL DEFAULT '',
`endereco` varchar(255) NULL DEFAULT NULL,
`cidade` varchar(255) NULL DEFAULT NULL,
`anoIngresso` smallint(6) NOT NULL DEFAULT 0,
PRIMARY KEY(`idCliente`)
) ENGINE=InnoDB;
In order to test, I will enter some records. Note that the client that should be returned contains an asterisk at the end of the name:
INSERT INTO `clientes` (`nome`, `endereco`, `cidade`, `anoIngresso`) VALUES
('João *', 'Rua A', 'Rio de Janeiro', 1992),
('José', 'Rua D', 'Rio de Janeiro', 1995),
('Joaquim', 'Rua H', 'Rio de Janeiro', 1997),
('Maria', 'Rua H', 'São Paulo', 2000),
('Janete', 'Rua 1', 'São Paulo', 1995),
('Malaquias *', 'Rua E', 'São Paulo', 1992),
('Zeca *', 'Rua X', 'Curitiba', 1997),
('Inácio', 'PF', 'Curitiba', 2018);
Finally, we will execute the query-solution:
SELECT `cl`.*
FROM `clientes` AS `cl`
INNER JOIN (
SELECT `cidade`, MIN(`anoIngresso`) AS `menorAno`
FROM `clientes`
GROUP BY `cidade`
) AS `cd`
ON `cl`.`cidade` = `cd`.`cidade` and `cl`.`anoIngresso` = `cd`.`menorAno`;
Returning:
+-----------+-------------+----------+----------------+-------------+
| idCliente | nome | endereco | cidade | anoIngresso |
+-----------+-------------+----------+----------------+-------------+
| 1 | João * | Rua A | Rio de Janeiro | 1992 |
| 6 | Malaquias * | Rua E | São Paulo | 1992 |
| 7 | Zeca * | Rua X | Curitiba | 1997 |
+-----------+-------------+----------+----------------+-------------+
3 rows in set (0.00 sec)
Example:
city A -- customer Joao
City B -- maria customer
city C -- customer Jose
Simply change the filter of the query:
SELECT `cl`.`cidade`, `cl`.`nome`
FROM `clientes` AS `cl`
INNER JOIN (
SELECT `cidade`, MIN(`anoIngresso`) AS `menorAno`
FROM `clientes`
GROUP BY `cidade`
) AS `cd`
ON `cl`.`cidade` = `cd`.`cidade` and `cl`.`anoIngresso` = `cd`.`menorAno`;
Returning:
+----------------+-------------+
| cidade | nome |
+----------------+-------------+
| Rio de Janeiro | João * |
| São Paulo | Malaquias * |
| Curitiba | Zeca * |
+----------------+-------------+
3 rows in set (0.00 sec)
A similar question has been solved here:
Sopt - How to get the value of a column corresponding to the maximum of another column?
Speak there, Mairon! Blz?! Just a tip: Post the structure of your table to make it easier for those who help you. Another thing that speeds up a lot is to post some records tb. ALWAYS as TEXT. Not as image, blz?!
– LipESprY
If possible, edit the question and ask what shape you are trying and are not getting the expected result.
– Gustavo Sampaio