Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get all 1st data of reference key in SQL

I have two tables named User and Payment. Where in Payment there is a foreign key of the user table. and here are the records of the Payment Table.

SELECT id,User_id FROM payment;

id User_id
1 1
2 1
3 2
4 3
5 2

But my expected output is this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

id User_id
1 1
3 2
4 3

I want only 1st data of every User_id in SQL.

>Solution :

Try this…

SELECT p1.id, p1.user_id
FROM payment p1
WHERE p1.id IN (SELECT MIN(p2.id) FROM payment p2 GROUP BY p2.user_id)

Assuming, by ‘first’ you mean the minimum value of the id in payment table for that user, and you want some more details also out of payment table OR do something else with it as well…

If you just want the MIN payment id, then simply this would work:

SELECT MIN(id), user_id FROM payment GROUP BY user_id
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading