[英]Adding a Subquery to a Query in SQL
I have a query that works very well. 我有一个很好的查询。 Let me start with it:
让我开始吧:
Edit: The SQL has been updated. 编辑: SQL已更新。 I get
0
in every row. 我每行得到
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;
I need to add one more function to it, where you see AS x
我需要再添加一个功能,在此您可以看到
AS x
Basically, there are three tables here that are important. 基本上,这里有三个重要的表格。
items
, reviews
and ratings
. items
, reviews
和ratings
。 In the top portion you see there are subqueries that are taking statistics such as averages and totals for each item. 在顶部,您看到子查询正在获取统计信息,例如每个项目的平均值和总计。
I need a final query that is tied to user_id
, item_id
and rate_id
(in ratings
). 我需要一个与
user_id
, item_id
和rate_id
(在ratings
)相关的最终查询。 In the end result, where it list each item and the stats with it, I want one more column, a simple true or false if logged in user has rated it. 在最终结果中,它列出了每个项目及其统计信息,我想要再增加一列,如果登录用户对它进行了评分,则该字段为true或false。 So I need something like this:
所以我需要这样的东西:
SELECT ???
FROM ratings AS r
WHERE r.user_id = '{$user_id}'
( user_id
of logged in user is passed in from PHP.`) (已登录用户的
user_id
从PHP传入。)
How can I make a subquery that gives me that last bit of info, but puts it in each row of items in the parent query? 我该如何做一个子查询,使我获得最后的信息,但是将其放在父查询的每一行中?
Add this to the parent query. 将此添加到父查询。
, coalesce(x.WasRated, 'false') as WasRated
Your x subquery is: 您的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
or something like it. 或类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.