从单个表获取通知并与多个表连接并生成单个数组

时间:2016-07-20 04:57:53

标签: php mysql codeigniter

我有一张像enter image description here

这样的表格

并从此表中选择所有通知并加入下面提到的表

  1. tbl_notice enter image description here

  2. tbl_task

  3. enter image description here

    1. tbl_assignment
    2. enter image description here

      我试图从像

      这样的表中获取数据
      $sql = "select * from(
          (
          SELECT a.refer_id as id ,a.refer_tbl,b.task_name as name FROM tbl_notification as a
          LEFT JOIN tbl_task as b ON (a.refer_id= b.task_id )ORDER BY a.created_date desc
          ) UNION
          (
          SELECT c.refer_id as id ,c.refer_tbl, d.notice_title as name FROM tbl_notification as c
          LEFT JOIN tbl_notice as d ON (c.refer_id = d.notice_id)ORDER BY c.created_date desc
          ) UNION
          ( 
          SELECT e.refer_id as id,e.refer_tbl, f.title as name FROM tbl_notification as e
          LEFT JOIN tbl_assignment as f ON (e.refer_id = f.assignment_id) ORDER BY e.created_date desc
          ))";
         $query= $this->db->query($sql)->get();
      

      结果显示第一个表中的数据连接(如果tbl_task)其他tbl_notice和tbl_assignment详细信息为null结果演示像这样 enter image description here

      请帮我纠正这个......

2 个答案:

答案 0 :(得分:1)

当你需要一个普通的(INNER)JOIN时,你正在执行LEFT(OUTER)JOIN。试试这个:

SELECT a.refer_id as id ,a.refer_tbl,b.task_name as name FROM tbl_notification as a
JOIN tbl_task as b ON (a.refer_id= b.task_id )ORDER BY a.created_date desc
UNION
SELECT c.refer_id as id ,c.refer_tbl, d.notice_title as name FROM tbl_notification as c
JOIN tbl_notice as d ON (c.refer_id = d.notice_id)ORDER BY c.created_date desc
UNION
SELECT e.refer_id as id,e.refer_tbl, f.title as name FROM tbl_notification as e
JOIN tbl_assignment as f ON (e.refer_id = f.assignment_id) ORDER BY e.created_date desc

答案 1 :(得分:0)

我得到了以下附加代码的答案

select * from ( SELECT a.refer_id as id ,a.refer_tbl,a.created_date,b.task_name as name FROM tbl_notification as a JOIN tbl_task as b ON (a.refer_id= b.task_id AND a.refer_tbl="tbl_task") 
           UNION SELECT c.refer_id as id ,c.refer_tbl,c.created_date, d.notice_title as name FROM tbl_notification as c JOIN tbl_notice as d ON (c.refer_id = d.notice_id AND c.refer_tbl="tbl_notice")
           UNION SELECT e.refer_id as id,e.refer_tbl,e.created_date, f.title as name FROM tbl_notification as e JOIN tbl_assignment as f ON (e.refer_id = f.assignment_id AND e.refer_tbl="tbl_assignment") ) tbl_notification ORDER BY `tbl_notification`.`created_date` desc

亲自帮助我......