Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join mysql tables

I've an old table like this:

user> id | name | address | comments

And now I've to create an "alias" table to allow some users to have an alias name for some reasons. I've created a new table 'user_alias' like this:

user_alias> name | user

But now I have a problem due my poor SQL level... How to join both tables to generate something like this:

1 | my_name    | my_address    | my_comments
1 | my_alias   | my_address    | my_comments
2 | other_name | other_address | other_comments

I mean, I want to make a "SELECT..." query that returns in the same format as the "user" table ALL users and ALL alias.. Something like this:

SELECT user.* FROM user LEFT JOIN user_alias ON `user`=`id`

but it doesn't work for me..

like image 542
Ivan Avatar asked Mar 23 '10 16:03

Ivan


People also ask

How do I join two tables in another database in MySQL?

You just need to prefix the table reference with the name of the database it resides in. – Yuval A. Is it possible to join to different DB's, DB1 = mysql & DB2 = PostgreSQL) . Both have few common tables.

What is join query in MySQL?

MySQL JOINS are used to retrieve data from multiple tables. A MySQL JOIN is performed whenever two or more tables are joined in a SQL statement. There are different types of MySQL joins: MySQL INNER JOIN (or sometimes called simple join) MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)


1 Answers

I think you need something like this:

SELECT user.*
FROM user
LEFT JOIN user_alias
ON user.name=user_alias.name

Your original query was not specific enough in the join condition.

like image 137
FrustratedWithFormsDesigner Avatar answered Oct 01 '22 19:10

FrustratedWithFormsDesigner