CDbCommand - 三个表Join和IN子句语法

时间:2013-01-14 19:25:31

标签: mysql sql yii

在我的Yii应用程序中,我有以下数据库结构:

Table user (id, firstName, lastName)
Table category (id, categoryName)
Table item (id, categoryId, name)
Table usergroup(id, userId, groupName)

我正在尝试运行以下查询:

$sql = 'SELECT a.id, a.firstName, a.lastName, b.id, b.categoryName, c.id, c.name
        FROM user AS a
        INNER JOIN (category AS b ON a.id = b.userId
        WHERE b.userId IN (SELECT f.id FROM usergroup f WHERE f.userId=:currentUserId))
        INNER JOIN item AS c ON b.id = c.categoryId
        WHERE c.name LIKE :listedName';

$command=$connection->createCommand($sql); 

$currentUserId = Yii::app()->user->id;
//binding :currentUserId  
$command->bindParam(":currentUserId", $currentUserId,PDO::PARAM_STR);

$listedItemName = $data->name;
//binding :listedItemName 
$command->bindParam(":listedName", $listedName,PDO::PARAM_STR);

$dataReader=$command->query();

然而,我得到了以下的理由:

CDbException

  

CDbCommand无法执行SQL语句:SQLSTATE [42000]:   语法错误或访问冲突:1064 SQL中有错误   句法;查看与MySQL服务器版本对应的手册   要在'ON a.id = b.userId WHERE b.userId IN附近使用正确的语法   (从第3行选择f.id FROM usergroup。

执行的SQL语句是:

SELECT a.id, a.firstName, a.lastName, b.id, b.categoryName, c.id, c.name FROM user AS a INNER JOIN (category AS b ON a.id = b.userId WHERE b.userId IN (SELECT f.id FROM usergroup f WHERE f.userId=:currentUserId)) INNER JOIN item AS c ON b.id = c.categoryId WHERE c.name LIKE :listedName. Bound with :currentUserId='2', :listedName='Oliver Twist'

任何形式的帮助或建议都将受到高度赞赏。谢谢!

2 个答案:

答案 0 :(得分:0)

你似乎有一些括号问题,也可能有一个不必要的子选择。我猜你正在寻找的是:

SELECT a.id, a.firstName, a.lastName, b.id, b.categoryName, c.id, c.name
FROM user AS a
INNER JOIN category AS b ON a.id = b.userId
INNER JOIN usergroup AS f ON f.userID = a.id
INNER JOIN item AS c ON b.id = c.categoryId
WHERE c.name LIKE :listedName'
AND  f.userID=:currentUserId;

但是,我不清楚项目和类别表之间的连接。您似乎没有在项目表中具有外来类别,只是加入项目ID和类别ID。

我也不清楚你在用户表和类别表之间的连接,你说的是用户id = category id。我不知道这些是如何相关的。

答案 1 :(得分:0)

更新/参考面临同一问题的任何其他人。我后来发现了SQL WHERE CLAUSE只能在语句结束时使用的问题,并且我用AND条件更改了第一个WHERE子句。这是工作查询:

$sql = 'SELECT a.id, a.firstName, a.lastName, b.id, b.categoryName, c.id, c.name
        FROM user AS a
        INNER JOIN (category AS b ON a.id = b.userId
        AND b.userId IN (SELECT f.id FROM usergroup f WHERE f.userId=:currentUserId))
        INNER JOIN item AS c ON b.id = c.categoryId
        WHERE c.name LIKE :listedName';