简体   繁体   中英

SQL Query: How to get data from three different tables

I am using mysql and here is the schema that I have.

First Table: Domains

+-----------+--------------------+---------------+
| domain_id | domain_name        | campaign_name |
+-----------+--------------------+---------------+
|        1  | test.org           | campaign 1    |
|        2  | example.org        | campaign 2    |
+-----------+--------------------+---------------+

Second Table: Users

+---------+-----------------+---------------+
| user_id | first_ame       | last_name     |
+---------+-----------------+---------------+
|       1 | John            | Zimmer        |
|       2 | Brian           | Roberts       |
|       3 | Jon             | McNeill       |
|       4 | Chris           | Lambert       |
|       5 | Vipul           | Patel         |
|       6 | Logan           | Green         |
+---------+-----------------+---------------+

Third Table: Emails

+----------+----------------------------------+-----------+---------+
| email_id | email                            | domain_id | user_id |
+----------+----------------------------------+-----------+---------+
|      1   | b1@test.org                      |        1  |      2  |
|      2   | b2@test.org                      |        1  |      1  |
|      3   | a1@example.org                   |        2  |      2  |
|      4   | a2@example.org                   |        2  |      3  |
|      5   | a3@example.org                   |        2  |      3  |
|      6   | a4@example.org                   |        2  |      4  |
+----------+----------------------------------+-----------+---------+

I want to get first_name, last_name and email of specific campaign ie campaign 2 as shown follow.

在此处输入图片说明

Here is Online DB Query Editor

Kindly guide me how can I write SQL query to accomplish that. Thanks

If I am not missing anything, this is basically a join . You have the ids nicely matched between the tables, so you can do:

SELECT u.*, e.email, d.campaign_name
FROM Users u JOIN
     Emails e
     ON u.user_id = e.user_id JOIN
     Domains d
     ON e.domain_id = d.domain_id
WHERE d.campaign_name = 'campaign 2';

The email table is a so called bridge table between the other two. You have to perform a join between the three tables:

SELECT first_name, last_name, email
FROM Domains JOIN Emails ON Domains.domain_id = Emails.domain_id JOIN Users ON Emails.user_id = Users.user_id
WHERE Domains.campaign_name = ...
SELECT first_name as 'First Name',last_name as 'Last Name', email as 'email ID',campaign_name as 'Compaign Name'
FROM Users u
inner join Emails e
on e.user_id = u.user_id
inner join Domains d
on d.domain_id = e.domain_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM