简体   繁体   English

PHP PDO多表联接

[英]PHP PDO Multiple Table join

I have multiple tables and I want to access the fields in a specific table. 我有多个表,我想访问特定表中的字段。 Here are the table schemas : 这是表schemas

在此处输入图片说明

Each tbl_acct has one tbl_unit . 每个tbl_acct具有一个tbl_unit A tbl_unit has many tbl_groups and a tbl_groupcontact consist of the contacts and the related group. 一个tbl_unit具有许多tbl_groups而一个tbl_groupcontact由联系人和相关组组成。 Every time I log in, I set a session where $_SESSION['unitid'] = $row['unitid']; 每次登录时,我都会设置一个会话,其中$_SESSION['unitid'] = $row['unitid']; .

What I wanted to do is to access the fields in the tbl_contacts . 我想做的是访问tbl_contacts的字段。 For now my code is here: 现在我的代码在这里:

$data = $conn->prepare("SELECT * FROM tbl_groups LEFT JOIN tbl_groupcontact ON tbl_groups.id=tbl_groupcontact.group_id WHERE tbl_groups.unitid = ?");
$data->execute(array($_SESSION['unitid']));
foreach ($data as $row) {
    echo $row['fname'] . " " . $row['lname']. "<br />"; 
}

As you can see, I can related the tbl_groups and tbl_groupcontact in my code however, I can't get the fields in the tbl_contacts . 如您所见,我可以在代码中关联tbl_groupstbl_groupcontact ,但是我无法在tbl_contacts获取字段。 Am I missing something here? 我在这里想念什么吗? Any help would be much appreciated. 任何帮助将非常感激。

You need to join another table. 您需要加入另一个表。

SELECT tbl_contacts.*
FROM tbl_groups
INNER JOIN tbl_groupcontact ON tbl_groupcontact.group_id = tbl_groups.id 
INNER JOIN tbl_contacts ON tbl_contacts.id = tbl_groupcontact.contact_id
WHERE tbl_groups.unitid = ?

No need for (slower) LEFT JOIN btw - use it when you want to retrieve records from (left-side) table even when there's no match found in joined (right-side) table (it's columns will be filled with nulls in this case). 不需要(慢速) LEFT JOIN btw-即使您在联接(右侧)表中没有找到匹配项时,也想从(左侧)表中检索记录时使用它(在这种情况下,其列将填充为空) )。

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

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