我有5张桌子,
user, plan, achievement, user_plan, user_achievement
结构
User
id
name
Plan
id
name
achievement
id
name
*planID
user_plan
*planid
*userid
user_achievement
*achievementid
*userid
*createDate
我使用Codeigniter(没关系,我想要的是mysql查询)
$this->db->select('*');
$this->db->from('user');
$query = $this->db->get();
实际上,对于每个计划,都有一个成就列表,如果没有实现,它不会存储在user_achievement中,那么我怎样才能“为每个用户,得到1”他的名字2)计划他加入,3)他取得的成就,而不是实现(需要突出成就)“?
感谢。
答案 0 :(得分:1)
使用join
$this->db->select('i.id,u.name,up.planid,p.name as planname,ua.achievementid,ach.name as ach_name');
$this->db->from('user as u');
$this->db->join('user_plan as up','up.userid = u.id','left');
$this->db->join('plan as p','p.id = up.planid','left');
$this->db->join('user_achievement as ua','ua.userid = u.id','left');
$this->db->join('achievement as ach','ach.id = ua.achievementid','left');
$query = $this->db->get();
答案 1 :(得分:1)
您需要在LEFT JOIN
,user
,plan
和achievement
之间user_achievement
,如下所示
select u.name as username,
p.name as planname,
a.name as achivementname
from User u
left join user_achievement ua on u.id = ua.userid
and ua.createDate is not null
left join achivement a on ua.achievementid = a.id
left join Plan p on a.planid = p.id