0

我有一个运行良好的查询。让我从它开始:

编辑: SQL 已更新。我进入0每一行。

   SELECT i.item, i.user_id, u.username,
        (COALESCE(r.ratetotal, 0)) AS total,
        (COALESCE(c.commtotal, 0)) AS comments,
        (COALESCE(r.rateav, '50%')) AS rate,
        (COALESCE(x.wasRated, '0')) AS wasRated
        FROM items AS i
        LEFT JOIN master_cat AS c
            ON (c.cat_id = i.cat_id)
        LEFT JOIN users AS u 
        ON u.user_id = i.user_id    
        LEFT JOIN
            (SELECT item_id, 
            COUNT(item_id) AS ratetotal, 
            AVG(rating) AS rateav 
            FROM ratings GROUP BY item_id) AS r 
        ON r.item_id = i.item_id
        LEFT JOIN
            (SELECT item_id, 
            COUNT(item_id) AS commtotal 
            FROM reviews GROUP BY item_id) AS c
        ON c.item_id = i.item_id
        LEFT JOIN
            (SELECT xu.user_id, ra.item_id, '1' AS wasRated
            FROM users AS xu
            LEFT JOIN ratings AS ra
                ON ra.user_id = xu.user_id
            WHERE xu.user_id = '1') AS x 
         ON x.user_id = u.user_id
              AND x.item_id = r.item_id
        WHERE c.category = 'Movies' 
        ORDER by i.item ASC;

我需要再添加一个功能,你看AS x

基本上,这里有三个重要的表。 items,reviewsratings. 在顶部,您会看到一些子查询正在获取统计信息,例如每个项目的平均值和总计。

我需要一个绑定到user_id,item_idrate_id(in ratings) 的最终查询。在最终结果中,它列出了每个项目及其统计信息,我想要一个多列,如果登录用户对其进行了评价,则为简单的真或假。所以我需要这样的东西:

SELECT ???
FROM ratings AS r
WHERE r.user_id = '{$user_id}'

user_id登录用户是从 PHP 传入的。`)

我怎样才能创建一个子查询,给我最后一点信息,但把它放在父查询的每一行项目中?

4

1 回答 1

1

将此添加到父查询。

, coalesce(x.WasRated, 'false') as WasRated

您的 x 子查询是:

(select users.user_id
 , ratings.item_id
, 'true' WasRated
from users join ratings on user.user_id = ratings.user_id
where users.user_id = the one for the logged in user
) x on x.user_id = users.user_id
and x.item_id = ratings.item_id

或类似的东西。

于 2013-02-16T23:01:34.057 回答