简体   繁体   English

MySQL-两表查询,带SUM

[英]MySQL - Two table query, with SUM

Question resolved 问题已解决

I have two tables, orders and customers, and I'd like to find all customers where orders is greater than 0. 我有两个表,订单和客户,我想查找订单大于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). (它仅给出一个结果,即客户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"). 订单中的客户字段和客户中的id字段具有相同的值(即订单1由客户5下达,客户ID 5为“约翰”)。

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. 当前的方法行得通,但是如果有大量的客户,效率将大大降低。

The reason your second query is returning only 1 row, is because oyu dont have a GROUP BY. 您的第二个查询仅返回1行的原因是因为oyu没有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. 与许多SQL数据库不同,MySQL确实允许您将未聚合的字段与已聚合的字段混合使用,即使它在技术上不是有效的sql,并且结果也是不可预测的。

Try 尝试

SELECT c.id, c.email, COUNT(o.customer) AS numOrders 
 FROM customers c 
  INNER JOIN orders o on (o.customer=c.email) 
  WHERE o.siteid= 'calico' 
 GROUP BY c.id, c.email

You can join the two tables like this: 您可以像这样连接两个表:

SELECT c.* 
FROM customers c
INNER JOIN orders o ON o.customer = c.id

Using an Inner Join will only result the customers that have entries in the orders table. 使用Inner Join只会导致在订单表中具有条目的客户。

SELECT c.*
     , COUNT(*) AS numOrders 
FROM customers c
  JOIN orders o 
    ON o.customer = c.id
WHERE o.siteid = 'calico'
GROUP BY c.id

Not sure if this would work, but you could try: 不知道这是否行得通,但是您可以尝试:

SELECT c.*, COUNT(o.customer) AS numOrders FROM customers c 
JOIN orders o on o.customer = c.id 
WHERE o.siteid= 'calico' AND o.customer=c.email AND numOrders > 0
GROUP BY c.id, c.email
SELECT
  customers.*,
  count(*) as ordercount
FROM customers
INNER JOIN orders ON customers.id=orders.customer
WHERE orders.siteid= 'calico'
GROUP BY customers.id;
SELECT c.id, c.email, COUNT(o.customer) AS numOrders 
FROM customers c, orders o 
WHERE o.siteid= 'calico' AND o.customer=c.email
GROUP BY c.id, c.email

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM