Get all the 1st data of the reference key in SQL
P粉041856955
P粉041856955 2023-09-11 21:36:51
0
2
452

I have two tables named "Users" and "Payments". In Payment, there is a foreign key to the users table. This is a record of the payment schedule.

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 only want the first data for each User_id in SQL.

P粉041856955
P粉041856955

reply all(2)
P粉510127741

You can use the GROUP BY clause on the User_id column.

P粉262073176

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)

Suppose, "first" refers to the smallest value of id in the payment table for that user, and you also need more details in the payment table or perform other operations on it...

If you just want the MIN payment ID, then just do this:

SELECT MIN(id), user_id FROM payment GROUP BY user_id
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!