MySql 在另一个选择中选择?
有什么办法可以做到这一点吗?
SELECT sum(price) from table2 WHERE id=(SELECT theid FROM table1 WHERE user_id="myid")
我有 table1,其中包含用户已购买的商品 ID。我想计算用户购买的所有商品的总和。
上述查询合法吗?如果不是,正确的形式是什么?
Is there any way to do this?
SELECT sum(price) from table2 WHERE id=(SELECT theid FROM table1 WHERE user_id="myid")
I have table1 with items' IDs, that a user has purchased. I want to calculate the sum of all items purchased by user.
Is the query above legal? If not, what's the correct form?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将
where id=(SELECT
更改为where id IN (SELECT
)或者您真正想要的可能是:
Change
where id=(SELECT
towhere id IN (SELECT
Or what you really want is probably:
只要 subselect 每次只返回一行,您的查询就可以。
如果返回更多行,您必须将查询更改为:
注意:在您的情况下,像其他人建议的那样简单的内部联接将更加可重用(并且可能会更快一点) ) - 但你写的绝对没问题(总是有多种方法可以得到想要的结果 - 现在总是很容易判断哪一个是“最好的”;-))
you query is ok, as long as the subselect is returning only one row every time.
if there are more rows returned, you'll have to change your query to:
NOTE: in you case, a simple inner join like others suggested would be much more redable (and maybe a tiny little bit faster) - but what you've written is absolutely ok (there are always multiple ways to get the desired result - and it's now always easy to tell wich one is "the best" ;-) )
您还可以使用 JOIN 语法
应该会给您相同的结果
You can also use the JOIN syntax
Should give you the same result
JOIN
会更具可读性:A
JOIN
would be more readable:您应该使用 SQL
JOIN
来提供该功能。You should use SQL
JOIN
to provide that functionality.