简体   繁体   English

MySQL:从相关表中获取数据

[英]MySQL: Acquiring data from related tables

I'm looking for help with acquiring and displaying information from related tables in MySQL. 我正在寻找有关从MySQL相关表中获取和显示信息的帮助。 I have two tables: 我有两个表:

  1. "table1" with columns id, name, surname “ table1”,具有列ID,名称,姓
  2. "table2" with columns id, phone 带有列ID的“ table2”,电话

They are related by the id columns. 它们通过id列关联。

I'm trying to display the name, surname and phone together. 我正在尝试同时显示姓名,姓氏和电话。 What I'm currently using is: 我当前正在使用的是:

SELECT name, surname, phone FROM table1, table2 WHERE table1.id = table2.id SELECT名称,姓氏,电话FROM table1,table2,其中table1.id = table2.id

However, I feel like I'm not using the relationship between the tables properly as I believe this would work between unrelated tables as well. 但是,我觉得我没有正确使用表之间的关系,因为我认为这在不相关的表之间也同样适用。

Also, not every id from table1 has a record in table2, meaning not everyone has a phone number. 另外,并非表1中的每个ID都在表2中有记录,这意味着并非每个人都有电话号码。 The method above results in only showing those id's that exist in both table1 and table2, while I want to display the data of those without a phone number as well, either by a blank space or a "N/A" in the phone column. 上面的方法仅显示表1和表2中都存在的ID,而我想通过电话列中的空格或“ N / A”显示没有电话号码的ID的数据。

Any tips on how to properly display the data are greatly appreciated. 非常感谢有关如何正确显示数据的任何提示。

You need to use an LEFT OUTER JOIN statement to join the two tables together. 您需要使用LEFT OUTER JOIN语句将两个表连接在一起。 LEFT OUTER JOIN will still show records from table1 even if there is no matching id in table2 . 即使在table2没有匹配的idLEFT OUTER JOIN仍将显示来自table1记录。 Something like: 就像是:

SELECT
    table1.name,
    table1.surname,
    table2.phone
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id

More info: https://www.w3schools.com/sql/sql_join_left.asp 更多信息: https : //www.w3schools.com/sql/sql_join_left.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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