[英]Having trouble JOINing 3 MySQL tables, retrieving data from two (CodeIgniter)
I have a database that has a structure like so (simplified for clarity): 我有一个数据库,其结构如下(为清楚起见而简化):
The query I'm attempting is, basically: "Get all tasks that are part of this group, along with all users that are assigned to that task" . 我尝试的查询基本上是: “获取属于该组的所有任务,以及分配给该任务的所有用户” 。
I've used JOIN queries in a few places on this project, but my understanding of them is basic, this unfortunately is a different scenario to the others. 我在这个项目的几个地方使用过JOIN查询,但是我对它们的理解是基本的,不幸的是,这与其他情况是不同的。 My attempt at a JOIN query seems to almost work, it looks like (CI Database class formatting, but hopefully it's clear what's happening regardless): 我对JOIN查询的尝试似乎几乎可以奏效,它看起来像(CI数据库类格式,但是希望无论发生什么事情都清楚):
$this->db->select('task.name AS taskname, user.name AS username');
$this->db->from('task');
$this->db->from('task_link');
$this->db->where('task.group', $group);
$this->db->join('user', 'user.id = task_link.user');
Edit: Dumped as a proper query for clarity: 编辑:为了清楚起见,转储为适当的查询:
SELECT `user`.`name` AS username, `task`.`name` AS taskname FROM (`task`, `task_link`) JOIN `user` ON `user`.`id` = `task_link`.`user` WHERE `task`.`group` = '7'"
I've tried the above with almost every combination of task, task_link and user and end up with the same results each time. 我已经尝试使用task,task_link和user的几乎每种组合进行上述操作,并且每次都得到相同的结果。 Main problems being: 主要问题是:
If it helps understand my model, the view would look something like: 如果它有助于理解我的模型,则视图将类似于:
foreach($tasks as $task){
echo $task->taskname;
foreach($task->username as $user){
echo $user;
}
}
I know that there are different JOIN clauses, and perhaps more relevant, grouping commands - but my brain is starting to hurt and I think I'm up against the edge of my mysql skills. 我知道有不同的JOIN子句,或者可能更相关的是对命令进行分组-但是我的大脑开始受伤了,我认为我的MySQL技能还很落后。
Is anyone able to lend a hand getting the above query to work as described? 有谁能伸出援手使上述查询按说明工作? Please just let me know if I've omitted something useful! 如果我省略了一些有用的信息,请告诉我!
I am guessing on how task_link and task are related but I think the basic SQL you want is: 我正在猜测task_link和task之间的关系,但我认为您想要的基本SQL是:
SELECT user.name AS username, task.name AS taskname
FROM task
INNER JOIN task_link ON task.id = task_link.task
INNER JOIN user ON user.id = task_link.user
WHERE task.group = '7'"
Which I think translates to this: 我认为这翻译成:
$this->db->select('task.name AS taskname, user.name AS username');
$this->db->from('task');
$this->db->where('task.group', $group);
$this->db->join('task_link', 'task.id = task_link.task');
$this->db->join('user', 'user.id = task_link.user');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.