codeigniter中的MySql union错误

时间:2014-04-15 05:56:42

标签: php mysql codeigniter union

我必须从两个表中获取值,我已经为两个表中的提取编写了单独的查询。并且两个查询都正常工作。但我需要在一个结果对象中得到它。所以我使用UNION运算符加入了查询。但它会引发一些错误。查询如下:

       $query1 = "SELECT dev_members.name,dev_members.id,dev_members.age,dev_members.family_id,dev_family.house_name,dev_ib_account_registration.account_id FROM (dev_members) 
            JOIN dev_family ON dev_family.id=dev_members.family_id
            JOIN dev_ib_account_registration ON dev_ib_account_registration.member_id=dev_members.id 

            UNION 

            SELECT dev_members.name,dev_members.id,dev_members.age,dev_members.family_id, dev_family.
            house_name,dev_ib_sub_member_registration.account_id FROM (dev_members) 
            JOIN dev_family  ON dev_family.id=dev_members.family_id
            JOIN dev_ib_sub_member_registration ON dev_ib_sub_member_registration.member_id=dev_members.id";

            $result = $this->db->query($query);
             return $result->result();

,错误是:

  

1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在'JOIN dev_family ON dev_family.id = dev_members.family_id JOIN dev_ib_s'第8行附近使用正确的语法

1 个答案:

答案 0 :(得分:2)

在第二个查询

中使用括号时会出现一些问题
(dev_members) <---

当我在Fiddle查询中使用没有它们的查询时,但使用括号会产生语法错误,因此请在没有()的情况下尝试使用

更新了查询

SELECT 
  dev_members.name,
  dev_members.id,
  dev_members.age,
  dev_members.family_id,
  dev_family.house_name,
  dev_ib_account_registration.account_id 
FROM
  dev_members
  JOIN dev_family 
    ON dev_family.id = dev_members.family_id 
  JOIN dev_ib_account_registration 
    ON dev_ib_account_registration.member_id = dev_members.id 
UNION
SELECT 
  dev_members.name,
  dev_members.id,
  dev_members.age,
  dev_members.family_id,
  dev_family.house_name,
  dev_ib_sub_member_registration.account_id 
FROM
  dev_members  
  JOIN dev_family 
    ON dev_family.id = dev_members.family_id 
  JOIN dev_ib_sub_member_registration 
    ON dev_ib_sub_member_registration.member_id = dev_members.id