简体   繁体   English

如何使用外键从三个表中选择所有数据

[英]How to select all data from three tables with a foreign key

Hi i am trying to select all data from three tables with a foreign key. 嗨,我正在尝试从具有外键的三个表中选择所有数据。 i have tried something like that 我已经尝试过类似的东西

$getId = $_GET['id'];

$getAll="SELECT * FROM employee_info ,over_view, employee_attendance
WHERE employee_info.id=$getId AND id=over_view.id AND id=employee_info.id";
$info_data = $dbcon->query($getAll);
$store = $info_data->fetch(PDO::FETCH_ASSOC);
echo $store['first_name'];

but it shows that error ans as a newbie i am finding it hard to solve. 但它表明错误 ans作为新手,我很难解决。 now how can i select all the data with a single query from three table over_view and employee_attendance tables id's are foreign key of employee_info. 现在,我该如何从三个表over_view和employee_attendance表ID中的单个查询中选择所有数据,这是employee_info的外键。

I think you need to qualify your column names in the WHERE clause as below 我认为您需要在WHERE子句中限定列名,如下所示

SELECT * 
  FROM employee_info
      ,over_view
      ,employee_attendance
 WHERE employee_info.id = $getId
   AND employee_info.id = over_view.id
   AND employee_attendance.id = employee_info.id

Ok. 好。 First of all: you are using the implicit join structure for your query while you should use the explicit one. 首先:您正在使用隐式联接结构进行查询,而应该使用显式联接结构。 Second, the error you get is because you have more than one column id in one of the tables and MySql needs to know what to take into consideration. 其次,您得到的错误是因为在一个表中有多个列ID,而MySql需要知道要考虑什么。 This is easier to see using the explicit join syntax: 使用显式联接语法更容易看到:

SELECT * 
    FROM employee_info
    JOIN over_view ON employee_info.id=over_view.id
    JOIN employee_attendance ON employee_info.id=employee_attendance.id
    WHERE employee_info.id = $getId

With explicit joins you can use all the functionalities of all the kinds of joins you can create between tables: left, right, inner... an easy to read guide to join is here 使用显式联接,您可以使用可以在表之间创建的各种联接的所有功能:左,右,内部...一个易于阅读的联接指南在这里

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

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