I have a table like this:
user_id | wants_user_id | state
And I want to select rows which are mutual and have a state column with value “yes” or “maybe”.
Example data:
Row 1: 1 | 2 | "yes"
Row 2: 2 | 1 | "maybe"
Row 3: 3 | 2 | "yes"
In this case I would like to select row 1 and 2 and on wants_user_id (second column) I would like to join user data from table users, but I can’t figure out the sql command.
Thank you for your help.
Use a self-join to get matching rows (I’m assuming “mutual rows” here means users that want each other):
In this case, you will get two “duplicate” rows, one for 1<->2 and one for 2<->1. To eliminate this, you can add a
AND b.user_id > a.user_idto the join condition – this will select only one row of each pair.