简体   繁体   中英

MySQL: Get all combinations

given I have a user table users :

user_id name
1 Bob
2 Adam
3 Charlie

Now I want to get all combinations of one or two users:

user1 user2
Bob NULL
Bob Adam
Bob Charlie
Adam NULL
Adam Bob
Adam Charlie
Charlie NULL
Charlie Bob
Charlie Adam

Assuming I want to get only two-person combinations, I would be simply able to do something like that:

SELECT * FROM users u1 
LEFT JOIN users u2 on u1.id!=u2.id

However, I want to include combinations with only one users. How can I get the desired result?

Use a self CROSS JOIN :

SELECT u1.name AS user1,
       NULLIF(u2.name, u1.name) AS user2
FROM users u1 CROSS JOIN users u2
ORDER BY u1.user_id, NULLIF(u2.user_id, u1.user_id);

See the demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM