我如何加入这3张桌子

时间:2018-03-20 12:48:21

标签: mysql sql codeigniter

这是SP_ARCHIVEenter image description here

这是Accountenter image description here

这是Proponententer image description here

查询应输出的内容为sp_archive.SP_IDsp_archive.SP_Titlesp_archive.SP_TypeAccount.Account_FirstNameAccount.MiddleNameAccount.LastName

name应该是不同的列

4 个答案:

答案 0 :(得分:0)

这应该做:

select  sp_archive.SP_ID, sp_archive.SP_Title, sp_archive.SP_Type, 
Account.Account_FirstName, Account.MiddleName, Account.LastName from 
SP_ARCHIVE join Proponent using (SP_ID) join Account using 
(Account_ID); 

答案 1 :(得分:0)

您可以针对您的问题尝试此查询:

$this->db->select('sp_archive.SP_ID, sp_archive.SP_Title, sp_archive.SP_Type, Account.Account_FirstName, Account.MiddleName, Account.LastName');
$this->db->from('Proponent');
$this->db->join('sp_archive', 'sp_archive.SP_ID=Proponent.SP_ID ', 'left');
$this->db->join('Account', 'Account.Account_ID = Proponent.Account_ID', 'left');

$query = $this->db->get();
$result = $query->result();

echo "<pre>";
print_r($result);
exit;

我希望它会有所帮助。

答案 2 :(得分:0)

您可以将帐户 SP_ARCHIVE 加入提升

SELECT `sp_archive`.`SP_ID`, 
       `sp_archive`.`SP_Title`, 
       `sp_archive`.`SP_Type`, 
       `Account`.`Account_FirstName`, 
       `Account`.`MiddleName`, 
       `Account`.`LastName` 
FROM `Proponent` 
LEFT JOIN `Account` 
       ON `Account`.`Account_ID` = `Proponent`.`Account_ID` 
LEFT JOIN `SP_ARCHIVE` 
       ON `SP_ARCHIVE`.`SP_ID` = `Proponent`.`SP_ID`

答案 3 :(得分:0)

查找CI查询构建器https://www.codeigniter.com/userguide3/database/query_builder.html

创建模型,然后创建一个函数将查询放入:

$select = 'av.SP_ID, sp_archive.SP_Title, av.SP_Type, a.Account_FirstName, a.MiddleName,a.LastName';

$results = $this->db->select($select)
//if you want it to be an inner join remove 3rd param from join
->join('sp_archive av', 'av.SP_ID=p.SP_ID ', 'left');
->join('Account a', 'a.Account_ID = p.Account_ID', 'left')
//aliase tabel names
->get('Proponent p')->result();

return $results;