我有两张桌子
表一是文件清单
文件:
+-------------+---------------+
| document_ID | document_name |
+-------------+---------------+
| 1 | test.pdf |
+-------------+---------------+
| 2 | other.pdf |
+-------------+---------------+
表二是使用该文档的用户列表。这是一种1-1关系 - 即用户只会使用文件ONCE(或根本不使用)。
documents_users:
+-------------+---------------+-----------+---------------+
| document_ID | user_ID | has_read | (other stuff) |
+-------------+---------------+-----------+---------------+
| 1 | 5 | 1 | stuff |
+-------------+---------------+-----------+---------------+
| 1 | 7 | 1 | stuff |
+-------------+---------------+-----------+---------------+
| 2 | 5 | 1 | stuff |
+-------------+---------------+-----------+---------------+
当用户浏览列表时 - 我需要能够显示所有文档,以及他们是否可以访问它
因此,例如,上例中用户5的所需输出是;
+-------------+---------------+-----------+---------------+
| document_ID | document_name | has_read | (other stuff) |
+-------------+---------------+-----------+---------------+
| 1 | test.pdf | 1 | stuff |
+-------------+---------------+-----------+---------------+
| 2 | other.pdf | 1 | stuff |
+-------------+---------------+-----------+---------------+
而用户7的所需输出是
+-------------+---------------+-----------+---------------+
| document_ID | document_name | has_read | (other stuff) |
+-------------+---------------+-----------+---------------+
| 1 | test.pdf | 1 | stuff |
+-------------+---------------+-----------+---------------+
| 2 | other.pdf | | |
+-------------+---------------+-----------+---------------+
我尝试按照
的方式进行连接$this->db->join('documents_users', 'documents_users.document_ID = documents.document_ID');
$this->db->where('documents_users.user_ID', '7');
return $this->get_all();
但这只会返回他们has_read = 1
的记录我可以看到问题是“where”命令 - 但我不知道该怎么办?
答案 0 :(得分:1)
您需要一个(左)外连接,user_ID
上的过滤条件移入连接条件而不是WHERE
子句:
$this->db->join(
'documents_users',
'documents_users.document_ID = documents.document_ID
AND documents_users.user_ID = 7',
'left'
);
答案 1 :(得分:0)
您需要STRAIGHT_JOIN:
SELECT a.document_ID, a.document_name, b.has_read,
FROM documents a
STRAIGHT_JOIN documents_users b
WHERE b.user_ID = 7;