skip to Main Content

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.

id User_id
1 1
3 2
4 3

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

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. You can use GROUP BY clause on the User_id column.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search