The question I’ve got here may look silly, but it drives me a bit crazy, as I can’t get how the MySQL join works.
I have 2 tables:
user;
+--------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| name | varchar(128) | NO | | NULL | |
+--------------------+--------------+------+-----+---------+-------+
game;
+--------------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+--------------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| source_id* | int(11) | NO | | NULL | |
| target_id* | int(11) | NO | | NULL | |
+--------------------+--------------+------+-----+---------+-------+
game.source_id and game.target_id are constraints that reference the user.id.
Now I want to select everything from game table and I want to include in the result names of 2 users, since game has 2 users. And I want those columns to be named as target_name and source_name specifically.
Tried this query:
SELECT
g.id,
u.name
FROM
game g
RIGHT JOIN
user u
ON
u.id = g.source_id
OR
u.id = g.target_id
WHERE
g.source_id = 1
OR
g.target_id = 1
;
But as you may have noticed, I don’t alias u.name as target_name or source_name because I don’t know how to do that and end result looks like this:
+----+------+
| id | name |
+----+------+
| 1 | bo |
| 1 | al |
| 2 | jo |
| 2 | jay |
+----+------+
As you can see, there’s a game appearing multiple times in the result.
Expected result:
+----+-------------+-------------+
| id | target_name | source_name |
+----+-------------+-------------+
| 1 | bo | al |
| 2 | jo | jay |
+----+-------------+-------------+
Thanks in advance.
you need to join the table
usertwice on tablegamein order to get the two names for the game. I have addedCOALESCEbecause it is useful for for showing descriptive value forNULLcolumns.If for instance there is no value for source or target, the value that will be shown is `-no value-.