0

我正在尝试使用 CDbCommandBuilder 在 Yii 中执行查询,以便将结果集保存在数组中。

问题是我不明白如何将我的 SQL (pgsql) 转换为 Yii CDbCommandBuilder 语法。主要是我的问题是嵌套连接。

查询:

SELECT  p.id
                up.id as fid,
                sum(CASE
                        WHEN v1.count>v2.count THEN v2.count
                            ELSE v1.count
                        END
                ) as res
        FROM product as v1
        INNER JOIN (
            SELECT p_id, count
            FROM product
            WHERE user_id = {$user_id}) as v2 on v1.p_id = v2.p_id and v1.user_id <> {$user_id}
        RIGHT JOIN users as p on p.id = v1.user_id
        INNER JOIN uf on uf.friend_id = p.id and uf.user_id = {$user_id} and is_active = true
        INNER JOIN up on up.user_id = p.id and is_active = true
        GROUP BY p.id, up.id
        ORDER BY res desc

任何人都可以帮忙吗?

谢谢

4

1 回答 1

1
$sql = "SELECT  p.id
                up.id as fid,
                sum(CASE
                        WHEN v1.count>v2.count THEN v2.count
                            ELSE v1.count
                        END
                ) as res
        FROM product as v1
        INNER JOIN (
            SELECT p_id, count
            FROM product
            WHERE user_id = :user_id) as v2 on v1.p_id = v2.p_id and v1.user_id <> :user_id
        RIGHT JOIN users as p on p.id = v1.user_id
        INNER JOIN uf on uf.friend_id = p.id and uf.user_id = :user_id and is_active = true
        INNER JOIN up on up.user_id = p.id and is_active = true
        GROUP BY p.id, up.id
        ORDER BY res desc";

$params = array(':user_id' => $user_id);
$aArrayOfRows = Yii::app()->db->createCommand($sql)->queryAll(true, $params);
于 2012-11-15T22:51:19.390 回答