关系MySQL - 获取属性?

时间:2010-03-17 02:59:48

标签: php mysql database relational-database

我目前正在使用以下PHP代码:

    // Get all subordinates
    $subords = array();
    $supervisorID = $this->session->userdata('supervisor_id');
    $result = $this->db->query(sprintf("SELECT * FROM users WHERE supervisor_id=%d AND id!=%d",$supervisorID, $supervisorID));
    $user_list_query = 'user_id='.$supervisorID;
    foreach($result->result() as $user){
        $user_list_query .= ' OR user_id='.$user->id;
        $subords[$user->id] = $user;
    }

    // Get Submissions
    $submissionsResult = $this->db->query(sprintf("SELECT * FROM submissions WHERE %s", $user_list_query));
    $submissions = array();
    foreach($submissionsResult->result() as $submission){
        $entriesResult = $this->db->query(sprintf("SELECT * FROM submittedentries WHERE timestamp=%d", $submission->timestamp));
        $entries = array();
        foreach($entriesResult->result() as $entries)   $entries[] = $entry;
        $submissions[] = array(
            'user' => $subords[$submission->user_id],
            'entries' => $entries
        );
        $entriesResult->free_result();
    }

基本上我得到的是一个给定supervisor_id下属的用户列表(每个用户条目都有一个supervisor_id字段),然后抓取属于这些用户的条目。

我不禁想到有一种更优雅的方式,比如SELECT FROM tablename where user->supervisor_id=2222

PHP / MySQL有这样的东西吗? 应该在某个时候适当地学习关系数据库。 :(

修改: 这是相关的架构

submissions
===============================
id, user_id, timestamp

submittedentries
===============================
id, user_id, timestamp

users
===============================
id, supervisor_id, email

一个submission有很多submittedentries,目前我通过使用时间戳来引用它。如果有人能提出更有效的方法,我会更愿意改变这一点。 (是的,还有更多我忽略的字段)

1 个答案:

答案 0 :(得分:2)

如果我的列名正确,那么应该从拥有指定主管的用户那里获取提交的列表。

SELECT * FROM users, submissions
WHERE users.supervisor_id = $supervisorID
AND submissions.user_id = users.id

此版本也尝试将时间戳检查结合起来。

SELECT * FROM users, submissions, submittedentries
WHERE users.supervisor_id = $supervisorID
AND submissions.user_id = users.id
AND submittedentries.timestamp = submissions.timestamp

编辑:已更新以匹配其他表格信息。我仍然不能100%确定第二个版本是否正确,需要针对数据库进行测试才能找到:)

哦,实际上你应该用你想要检索的实际列的名称替换星号。