J'ai une table comme suit et ce que je veux, c'est utiliser obtenir la ligne initiale avec le moins d'identifiant de chaque groupe UID.
La table est la suivante P>
_id uid type cnt 5 a aaa 1 2 b bbb 2
3 Réponses :
Vous pouvez essayer ceci:
SELECT t1.*, t2.cnt FROM table t1 INNER JOIN ( SELECT MIN(_id) AS id, COUNT(_id) AS cnt FROM table WHERE type IN ('aaa','bbb') GROUP BY uid ) t2 ON t1._id = t2.id ORDER BY t1.uid
Si vous exécutez MySQL 8.0, vous pouvez simplement utiliser les fonctions de fenêtre pour cela:
select _id, uid, type, cnt from ( select t.*, count(*) over(partition by uid) cnt, row_number() over(partition by uid order by _id) rn from mytable t where type in ('aaa', 'bbb') ) t where rn = 1
Vous pouvez le faire sans subquiery. Dans MySQL 8+, vous pouvez utiliser cette logique:
SELECT MIN(_id) as _id, uid, SUBSTRING_INDEX(GROUP_CONCAT(type ORDER BY _id), ',', 1) as type, COUNT(*) as cnt FROM table WHERE type IN ('aaa', 'bbb') GROUP BY uid;