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?
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);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With