Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two tables in a query

Tags:

sql

join

mysql

I have two tables. The first is user; this consists of username and userid. The second is search which consists of userid and query.

When I select the search table I want user ID to be replaced by username by taking the data from the user table. Is this making sense?

userid username
1 foo1
2 foo2
3 foo3
4 foo4
userid query
1 blah1
2 blah2
3 blah2
4 blah2

Is there a way to do this with a single query?

like image 922
Ben Shelock Avatar asked Jul 17 '09 06:07

Ben Shelock


People also ask

How can I merge two tables in SQL query?

Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other). Below is the generic syntax of SQL joins. USING (id);

How can I get data from two tables in a single query?

In SQL, to fetch data from multiple tables, the join operator is used. The join operator adds or removes rows in the virtual table that is used by SQL server to process data before the other steps of the query consume the data.


1 Answers

You are looking for an inner join. This would do it:

SELECT s.query, u.username
FROM search s
INNER JOIN users u
ON s.userid = u.userid
like image 82
Paolo Bergantino Avatar answered Sep 22 '22 07:09

Paolo Bergantino