Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select two additional columns from another table based on values in the main table?

Tags:

mysql

I have a table named maintable with 3 columns: id, userid1 and userid2.

Another table named users is keyed by userid, and has name as a column.

I want to select something along the lines of:

SELECT maintable.*, users.name AS username1, users.name AS username2 
FROM maintable, users 
WHERE ...

Basically I want to get all the columns in the maintable row, and add two columns at the end that will draw the names for userid1 and userid2 from the users table.

I'm unsure how to format the where clause for a query like this.

like image 886
CP1985 Avatar asked Feb 15 '11 17:02

CP1985


People also ask

How do I SELECT two columns in a table?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

Can we use two columns in where clause in SQL?

Answer. Yes, within a WHERE clause you can compare the values of two columns.


1 Answers

You need to join twice with users:

SELECT m.*, u1.name, u2.name
FROM maintable m 
INNER JOIN users u1 ON (m.userid1 = u1.userid)
INNER JOIN users u2 ON (m.userid2 = u2.userid)

You can read the documentation about MySQL JOIN Syntax here.

like image 178
Pablo Santa Cruz Avatar answered Sep 28 '22 00:09

Pablo Santa Cruz