如何有效地从多个表中查询子记录?

时间:2010-02-19 15:32:42

标签: php sql codeigniter

我们有一个简单的数据库。 User表保存用户。 Accounts表包含每个用户的多个帐户。 “主题”表包含每个帐户的多个主题。

因此,用户将拥有多个帐户,每个帐户将拥有多个主题。那么,如果我有一个id = 1的用户,我如何有效地查询所有3个表来获取该用户的所有帐户和主题?

我目前正在使用运行许多sql查询的foreach循环。有没有办法只运行一个SQL查询来获得我想要的东西?

这是我正在使用的代码(CodeIgniter代码):

$data=array();
$accounts=$this->db->get_where('accounts',array('user_id'=>1));
foreach ($accounts->result() as $account) {
    $tmp=array();
    $topics=$this->db->get_where('topics',array('account_id'=>$account->id));
    foreach ($topics->result() as $topic) {
        $this->db->order_by($order_by);
        $terms=$this->db->get_where('terms',array('topic_id'=>$topic->id));
        array_push($tmp,array('topic'=>$topic, 'terms'=>$terms->result()));
    }
    array_push($data,array('account'=>$account, 'topics'=>$tmp));
}
return $data;

2 个答案:

答案 0 :(得分:3)

只需一对多与另一对多。

用户 - >多个帐户

帐户 - >许多话题

想想你的用户表,一行是唯一的(包含一个用户说Jon Doe)。 想想您的帐户表引用某种用户(即多个帐户可以包含相同的用户,此外,帐户Acme 1和Acme 2都属于用户Jon Doe)。 最后,请考虑包含对帐户的引用的主题表。这是每个主题都有一个帐户ID。这意味着帐户有许多与之相关的主题。

SELECT
   u.UserID,
   a.Account
   t.Topic
FROM 
    Users u
INNER JOIN 
     Accounts a
ON u.UserID = a.UserID
INNER JOIN
     Topics t
ON t.AccountID = a.AccountID

如果您想缩小一个用户,只需添加WHERE子句:

SELECT
   u.UserID,
   a.Account
   t.Topic
FROM 
    Users u
INNER JOIN 
     Accounts a
ON u.UserID = a.UserID
INNER JOIN
     Topics t
ON t.AccountID = a.AccountID
WHERE u.UserID=1

答案 1 :(得分:0)

SELECT top.`topic_id` [etc]
FROM `accounts` acc
JOIN `topics` top ON (top.`account_id` = acc.`id`)
WHERE acc.`member_id` = 1

是基本查询,不确定CI。

如果您需要会员ID中的其他信息,请:

SELECT usr.`id`, acc.`account_id`, top.`topic_id` [etc]
FROM `users` usr
JOIN `accounts` acc ON (acc.`member_id` = usr.`id`)
JOIN `topics` top ON (top.`account_id` = acc.`id`)
WHERE usr.`id` = 1