0

在我的 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();

但是,我得到以下例外:

CDb异常

CDbCommand 执行 SQL 语句失败:SQLSTATE[42000]: Syntax error or access violation: 1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 3 行的 'ON a.id = b.userId WHERE b.userId IN (SELECT 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'

任何形式的帮助或建议将不胜感激。谢谢你!

4

2 回答 2

0

对于面临相同问题的任何其他人的更新/参考。后来我发现SQL WHERE CLAUSE只能用在语句末尾的问题,我把第一个WHERE子句改成了AND条件。这是工作查询:

$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';
于 2013-01-15T20:56:27.533 回答
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 = 类别 id。我看不出这些有什么关系。

于 2013-01-14T19:38:01.327 回答