Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Basics: How to get details from multiple tables in one query?

Tags:

sql

I've used SQL for years but have never truly harnessed its potential.

For this example let's say I have two tables:

CREATE TABLE messages (
    MessageID INTEGER NOT NULL PRIMARY KEY,
    UserID INTEGER,
    Timestamp INTEGER,
    Msg TEXT);

CREATE TABLE users (
    UserID INTEGER NOT NULL PRIMARY KEY,
    UserName TEXT,
    Age INTEGER,
    Gender INTEGER,
    WebURL TEXT);

As I understand it, PRIMARY KEY basically indexes the field so that it can be used as a rapid search later on - querying based on exact values of the primary key gets results extremely quickly even in huge tables. (which also enforces that the field must be unqiue in each record.)

In my current workflow, I'd do something like

SELECT * FROM messages;

and then in code, for each message, do:

SELECT * FROM users WHERE UserID = results['UserID'];

This obviously sounds very inefficient and I know it can be done a lot better.

What I want to end up with is a result set that contains all of the fields from messages, except that instead of the UserID field, it contains all of the fields from the users table that match that given UserID.

Could someone please give me a quick primer on how this sort of thing can be accomplished?

If it matters, I'm using SQLite3 as an SQL engine, but I also would possibly want to do this on MySQL.

Thank you!

like image 481
fdmillion Avatar asked Jul 29 '13 05:07

fdmillion


People also ask

How do I SELECT information from multiple tables in SQL?

In SQL we can retrieve data from multiple tables also by using SELECT with multiple tables which actually results in CROSS JOIN of all the tables. The resulting table occurring from CROSS JOIN of two contains all the row combinations of the 2nd table which is a Cartesian product of tables.

How can I get data from multiple tables?

You can also merge data from two or more tables or views into a single column or create a subquery to retrieve data from several tables. You can use a SELECT statement to join columns in two or more tables. You can merge data from two or more tables into a single column on a report by using the keyword UNION.

How do I combine data from multiple tables into one table in SQL?

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).


1 Answers

Not sure about the requested order, but you can adapt it.
Just JOIN the tables on UserID

SELECT MESSAGES.*, 
       USERS.USERNAME, 
       USERS.AGE, 
       USERS.GENDER, 
       USERS.WEBURL 
FROM   MESSAGES 
       JOIN USERS 
         ON USERS.USERID = MESSAGES.USERID 
ORDER  BY MESSAGES.USERID, 
          MESSAGES.TIMESTAMP 
like image 87
bummi Avatar answered Nov 14 '22 22:11

bummi