【问题标题】:MySQL query select from multiple tables, display all from table1 + some data from table2MySQL查询从多个表中选择,显示来自table1的所有数据+来自table2的一些数据
【发布时间】:2015-05-11 15:08:43
【问题描述】:

我有 2 张桌子。我想打印出 table1 中的所有访问列表,以及 table2 中的 接口。但是一些访问列表没有与访问列表关联的接口(但我仍然想打印这些访问列表)。我该怎么做呢? (我就是无法得到想要的结果._。)

表1

| id | access-list  | ... 
+----+--------------+ 
| 0  | list_1       | ...
| 1  | list_2       | ...
| 2  | list_3       | ...
| 3  | list_4       | ...

表2

| id | access-list  | interface |
+----+--------------+-----------+
| 0  | list_1       | iface0    |
| 1  | list_4       | iface1    |

预期结果:

0 list_1 iface0 bla bla bla 
1 list_2        bla bla bla
2 list_3        bla bla bla 
3 list_4 iface1 bla bla bla

【问题讨论】:

    标签: php mysql


    【解决方案1】:
    SELECT *
    FROM table1 t1
    LEFT JOIN table2 t2
        ON t1.access_list = t2.access_list
    

    当您需要一个表中的所有数据,并且只需要另一个表中匹配的数据时,OUTER JOIN 通常是要走的路。 LEFT JOIN 实际上是LEFT OUTER JOIN 的缩写,它指定哪个表(JOIN 语句左侧的那个)将返回所有数据。您始终可以使用RIGHT JOIN 并以相反的方式命名表(即table1 LEFT JOIN table2 等同于table2 RIGHT JOIN table1),但LEFT JOIN 语法更为常见。

    只从两个表返回匹配数据的连接称为INNER JOIN,通常缩写为JOIN

    【讨论】:

    • 我建议您在答案中添加一些解释。纯代码的答案可能已经足够好了,但代码+解释的答案总是更好
    • @Barranka - 说得好,做得好。我已经编辑了一些更详细的内容。
    • 感谢 TobyLL,做到了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2021-12-25
    • 2020-08-12
    相关资源
    最近更新 更多