如何在表JOIN,Active Records Codeigniter中添加括号

时间:2012-04-05 07:06:20

标签: php mysql codeigniter activerecord

我正在使用codeigniter活动记录,我想创建一个talbe join

这是我的查询

    $table = $this->mastables ['table1'];
    $table1 = $this->mastables ['table2'];

    $this->db->select ( 'a.RelationshipCategoryName,a.RelationshipCategoryID,COUNT( b.ShopRelationshipID ) AS count' );
    $this->db->from ( $table . " as a" );
    $this->db->join ( $table1 . " as b", "(( a.RelationshipCategoryID=b.RecieverRelationshipCategory AND b.3rdPartyID=" .$shop_id. " ) OR (  a.RelationshipCategoryID=b.SenderRelationshipCategory AND b.ShopID=" .$shop_id. " )) AND b.IsDelete!=1", 'left' );
    $this->db->where ( 'a.ShopID', $shop_id );

    $this->db->where ( 'a.IsActive', 1 );

    if ($limit != NULL) {
        $this->db->limit ( $limit, $offset );
    }
    if ($oderby != NULL && $oder != NULL) {
        $this->db->order_by ( $oderby, $oder );
    }

    $this->db->group_by ( 'a.RelationshipCategoryID' );

    $query = $this->db->get ();
    if ($query->num_rows () > 0) {
        return $query->result_array ();
    } else {
        return FALSE;
    }

错误是

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') OR ( a.RelationshipCategoryID=b.SenderRelationshipCategory AND b.ShopID=11 )) ' at line 3

SELECT `a`.`RelationshipCategoryName`, `a`.`RelationshipCategoryID`, COUNT( b.ShopRelationshipID ) AS count FROM (`mas_shop_relationship_category` as a) LEFT JOIN `mas_shop_relationship` as b ON `a`.`RelationshipCategoryID`=`b`.`RecieverRelationshipCategory` AND b.3rdPartyID=11 ) OR ( a.RelationshipCategoryID=b.SenderRelationshipCategory AND b.ShopID=11 )) AND b.IsDelete!=1 WHERE `a`.`ShopID` = '11' AND `a`.`IsActive` = 1 GROUP BY `a`.`RelationshipCategoryID` ORDER BY `a`.`RelationshipCategoryName` asc LIMIT 5

Filename: C:\xampp\htdocs\elephanti2\system\database\DB_driver.php

Line Number: 330

错误来自这一行

    $this->db->join ( $table1 . " as b", "(( a.RelationshipCategoryID=b.RecieverRelationshipCategory AND b.3rdPartyID=" .$shop_id. " ) OR (  a.RelationshipCategoryID=b.SenderRelationshipCategory AND b.ShopID=" .$shop_id. " )) AND b.IsDelete!=1", 'left' );

如何在我的代码中正确添加这部分代码

(( a.RelationshipCategoryID=b.RecieverRelationshipCategory AND b.3rdPartyID=" .$shop_id. " ) OR (  a.RelationshipCategoryID=b.SenderRelationshipCategory AND b.ShopID=" .$shop_id. " ))

1 个答案:

答案 0 :(得分:0)

似乎查询生成2个paranthesess从此处转义(( a.RelationshipCategoryID=b..再次检查您的查询。同样对于db->select(),您应该将false作为第二个参数传递给不要转义特殊字符

$this->db->select ('select query', false);

最好只使用$this->db->query('whole sql query');进行复杂查询