Yii条件条件不工作SQL错误

时间:2014-05-19 12:13:36

标签: php mysql yii

$criteria->condition .= 'UserID = '.$userId.' UNION
(
    SELECT * FROM display WHERE 
    UserID IN 
    (
        SELECT DISTINCT UserID FROM lkusergroup WHERE 
        GroupID IN
        (
            SELECT GroupID FROM lkusergroup WHERE UserID = '.$userId.'
        )
    )
)';

我试图执行上面的代码,但却出现以下错误

    CDbCommand failed to execute the SQL statement: SQLSTATE[21000]: 
Cardinality violation: 1222 The used SELECT statements have a different number of columns. The SQL statement executed was:
SELECT COUNT(*) FROM `display` `t` WHERE UserID = 2 UNION
        (
        SELECT * FROM display WHERE
        UserID IN
        (
        SELECT DISTINCT UserID FROM lkusergroup WHERE
        GroupID IN
        (
        SELECT GroupID FROM lkusergroup WHERE UserID = 2
        )
        )
    ) 

为什么查询生成计数(*)这是实际问题。我试过可能解决这个错误的方法bt没有任何建议吗?

1 个答案:

答案 0 :(得分:0)

您还需要在下面的行中添加计数功能:

SELECT * FROM display WHERE 
    UserID IN 

您的代码必须是:

$criteria->condition .= 'UserID = '.$userId.' UNION
(
    SELECT count(*) FROM display WHERE 
    UserID IN 
    (
        SELECT DISTINCT UserID FROM lkusergroup WHERE 
        GroupID IN
        (
            SELECT GroupID FROM lkusergroup WHERE UserID = '.$userId.'
        )
    )
)';

在UNION时,必须从查询中返回相同数量的列。

<强>编辑:

您的查询必须如下:

SELECT COUNT(*), * FROM display WHERE
    UserID IN
    (
       SELECT DISTINCT UserID FROM lkusergroup WHERE
        GroupID IN
        (
           SELECT GroupID FROM lkusergroup WHERE UserID = 2
        )
    )