'How to sql for each id?
I am running this SQL statement:
SELECT *
FROM users
WHERE id IN (6, 8, 8)
GROUP BY id
I want to get something like this:
| id | name |
+----+------+
| 6 | Joe |
| 8 | Alex |
| 8 | Alex |
How to do it? For each id get one found row?
Solution 1:[1]
If we query one table without using DISTINCT, JOIN or GROUP BY etc. we get the same number or rows returned as there are in the table which meet the WHERE condition if there is one.
We can force duplication by joining to a fictive table with duplicate lines.
create table users (id int, name varchar(10)); insert into users values (4,'Bill'),(6,'Joe'),(8,'Alex');
SELECT * FROM users WHERE id IN (6, 8, 8);id | name -: | :--- 6 | Joe 8 | Alex
SELECT u.id, u.name FROM users AS u JOIN ( SELECT 6 AS id UNION ALL SELECT 8 UNION ALL SELECT 8) AS i ON u.id = i.id
id | name -: | :--- 6 | Joe 8 | Alex 8 | Alex
db<>fiddle here
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
