MySQL - 两个表查询,带有 SUM
问题已解决
我有两个表,订单和客户,我想找到订单大于 0 的所有客户。
我目前使用两个查询:
SELECT * FROM customers
我
SELECT count(id)
FROM orders
WHERE customer='CUSTOMER_VALUE'
AND siteid='siteid'
想将其变成一个查询,因此它会找到在商店中下了一个或多个订单的所有客户。
我尝试了以下操作,但不起作用:(
SELECT c.*,
COUNT(o.customer) AS numOrders
FROM customers c,
orders o
WHERE o.siteid= 'calico'
AND o.customer=c.email
它只给出一个结果,即客户 ID 1)。
我只需要找到订单值以及客户表中的一些值。
订单中的客户字段和客户中的 id 字段具有相同的值(即订单 1 是由客户 5 下的,客户 id 5 是“John”)。
有什么办法可以做到这一点吗?
目前的方式是可行的,但是如果客户量很大的话,效率就非常低了。
Question resolved
I have two tables, orders and customers, and I'd like to find all customers where orders is greater than 0.
I currently use two queries:
SELECT * FROM customers
and
SELECT count(id)
FROM orders
WHERE customer='CUSTOMER_VALUE'
AND siteid='siteid'
I'd like to turn this into one query, so it finds all customers where they've placed one or more orders in the store.
I tried the following, but it doesn't work:
SELECT c.*,
COUNT(o.customer) AS numOrders
FROM customers c,
orders o
WHERE o.siteid= 'calico'
AND o.customer=c.email
(it only gives one result, which is customer ID 1).
I only need to find the orders value, and a few values from the customers table.
The customer field in orders and the id field in customers are the same value (ie order 1 was placed by customer 5, customer id 5 is "John").
Is there any way to do this?
The current way works, but it would be greatly inefficient if there was to be a large amount of customers.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您的第二个查询仅返回 1 行的原因是因为 oyu 没有 GROUP BY。与许多 SQL 数据库不同,MySQL 确实允许您将非聚合字段与聚合字段混合在一起,即使它在技术上是无效的 sql,并且结果是不可预测的。
尝试
The reason your second query is returning only 1 row, is because oyu dont have a GROUP BY. Unlike many SQL databases, MySQL does allow you to mix non-aggregated fields with aggregated ones, even though its technically not valid sql, and the results are unpredictable.
Try
您可以像这样连接两个表:
使用
内部连接
只会生成在订单表中具有条目的客户。You can join the two tables like this:
Using an
Inner Join
will only result the customers that have entries in the orders table.不确定这是否有效,但你可以尝试:
Not sure if this would work, but you could try: