MySql 在另一个选择中选择?

发布于 2024-10-10 10:59:37 字数 217 浏览 1 评论 0原文

有什么办法可以做到这一点吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

芯好空 2024-10-17 10:59:37

where id=(SELECT 更改为 where id IN (SELECT)

或者您真正想要的可能是:

SELECT sum(price) FROM table2 INNER JOIN table1 ON table2.id = table1.theid WHERE table1.user_id = 'my_id'

Change where id=(SELECT to where id IN (SELECT

Or what you really want is probably:

SELECT sum(price) FROM table2 INNER JOIN table1 ON table2.id = table1.theid WHERE table1.user_id = 'my_id'
栀梦 2024-10-17 10:59:37

只要 subselect 每次只返回一行,您的查询就可以。

如果返回更多行,您必须将查询更改为:

[...] WHERE id IN (SELECT [...]

注意:在您的情况下,像其他人建议的那样简单的内部联接将更加可重用(并且可能会更快一点) ) - 但你写的绝对没问题(总是有多种方法可以得到想要的结果 - 现在总是很容易判断哪一个是“最好的”;-))

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:

[...] WHERE id IN (SELECT [...]

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" ;-) )

半世蒼涼 2024-10-17 10:59:37

您还可以使用 JOIN 语法

SELECT sum(price) from table2 t2
join table1 t1 on t1.theID = t2.id
WHERE t1.user_id="myid"

应该会给您相同的结果

You can also use the JOIN syntax

SELECT sum(price) from table2 t2
join table1 t1 on t1.theID = t2.id
WHERE t1.user_id="myid"

Should give you the same result

情定在深秋 2024-10-17 10:59:37

JOIN 会更具可读性:

SELECT SUM(price) FROM table2
INNER JOIN table1 ON table2.id = table1.theid
WHERE table1.user_id = "myid"

A JOIN would be more readable:

SELECT SUM(price) FROM table2
INNER JOIN table1 ON table2.id = table1.theid
WHERE table1.user_id = "myid"
酒绊 2024-10-17 10:59:37

您应该使用 SQL JOIN 来提供该功能。

SELECT SUM(table2.price) JOIN table1 ON
table2.id=table1.theid WHERE table1.user_id="myid"

You should use SQL JOIN to provide that functionality.

SELECT SUM(table2.price) JOIN table1 ON
table2.id=table1.theid WHERE table1.user_id="myid"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文