SQL查询:如何从三个不同的表中获取数据

时间:2019-08-28 21:43:07

标签: mysql sql join select

我正在使用mysql,这是我拥有的架构。

第一张表:Domains

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

第二张表: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         |
+---------+-----------------+---------------+

第三张表: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  |
+----------+----------------------------------+-----------+---------+

我想获得first_name, last_name and email of specific campaign即第2个广告系列,如下所示。

git: list all files added/modified on a day (or week/month…)

这里是repos

请指导我如何编写SQL查询来完成该任务。谢谢

3 个答案:

答案 0 :(得分:2)

如果我什么都不缺,那基本上就是join。您可以在表之间很好地匹配ID,因此您可以执行以下操作:

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';

答案 1 :(得分:2)

电子邮件表是其他两个表之间的所谓桥接表。您必须在三个表之间执行联接:

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

答案 2 :(得分:2)

sqlite3_open()