Note that there are some explanatory texts on larger screens.

plurals
  1. POMySQL: How to combine a column referenced multiple times from another table and assign proper aliases?
    primarykey
    data
    text
    <p>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.</p> <p>I have 2 tables:</p> <pre><code>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 | | +--------------------+--------------+------+-----+---------+-------+ </code></pre> <p><code>game.source_id</code> and <code>game.target_id</code> are constraints that reference the <code>user.id</code>.</p> <p>Now I want to select everything from <code>game</code> table and I want to include in the result names of 2 users, since <code>game</code> has 2 users. And I want those columns to be named as <code>target_name</code> and <code>source_name</code> specifically.</p> <p><strong>Tried this query</strong>:</p> <pre><code>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 ; </code></pre> <p>But as you may have noticed, I don't alias <code>u.name</code> as <code>target_name</code> or <code>source_name</code> because I don't know how to do that and end result looks like this:</p> <pre><code>+----+------+ | id | name | +----+------+ | 1 | bo | | 1 | al | | 2 | jo | | 2 | jay | +----+------+ </code></pre> <p>As you can see, there's a <code>game</code> appearing multiple times in the result.</p> <p><strong>Expected result:</strong></p> <pre><code>+----+-------------+-------------+ | id | target_name | source_name | +----+-------------+-------------+ | 1 | bo | al | | 2 | jo | jay | +----+-------------+-------------+ </code></pre> <p>Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload