在SQL中向查询添加子查询

时间:2013-02-16 22:26:11

标签: mysql sql subquery

我的查询效果非常好。让我先说吧:

编辑: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

基本上,这里有三个表很重要。 itemsreviewsratings。在顶部,您会看到有子查询正在记录每个项目的平均值和总计等。

我需要一个与user_iditem_idrate_idratings)相关联的最终查询。在最终结果中,它列出了每个项目以及带有它的统计数据,我想要一个列,如果登录用户已对其进行评级,则需要一个简单的真或假。所以我需要这样的东西:

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

(已登录用户的user_id从PHP传入。)

如何创建一个子查询,它给我最后一点信息,但是将它放在父查询中的每一行项目中?

1 个答案:

答案 0 :(得分: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

或类似的东西。