cher tout ce que j'ai utilisateurs forts> table et et j'ai suivi Rejoignez la requête for forte>: p> select
users.id as user_id,
users.username,
users.job,
cars.id,
cars.brand as car_brand
FROM users
LEFT JOIN cars on users.id = cars.user_id
GROUP BY users.username, users.id, cars.id;
3 Réponses :
You can do in this was as well.
select
users.id as user_id,
users.username,
users.job,
cars.id,
cars.brand as car_brand
FROM users
LEFT JOIN cars on users.id = cars.user_id
where exists (select username, count(*) multiplecars
FROM users u
JOIN cars c on u.id = c.user_id
where users.username = u.username
group by
u.username
having count(*) > 1 )
If the users have more than one car (even if same brand then this will bring those records) if you only want users with more than one branded care you can do count(distinct)
@YUSUFIBRAHIM Je suis content que cela vous ait aidé :)
SELECT users.username
FROM users
WHERE users.id IN(
select
users.id
FROM users
JOIN cars on users.id = cars.user_id
GROUP BY users.id
HAVING COUNT(*) > 1
);
Filter users first who has more then one car then get corresponding details
La méthode la plus simple et la plupart des performances est d'utiliser les fonctions de fenêtres:
select user_id, username, job, id, brand
from (select u.id as user_id, u.username, u.job,
c.id, c.brand as car_brand,
count(*) over (partition by u.id) as num_cars
from users u join
cars c
on u.id = c.user_id
) uc
where num_cars > 1;
Groupe par ... ayant compté (*)> 1. N'incluez pas l'identifiant de la voiture dans votre regroupement, car cela entraînerait une pièce par groupe après tout
Pourquoi votre colonne
car_brand code> semble-t-elle avoir des valeurs manquantes? Pouvez-vous nous montrer la sortie attendue?Regarde la réponse d'Avi, ça marche très bien sur mon cas.