2012-06-06 153 views
0

好的伙计们,很抱歉,因为我看到了一些mysql JOIN示例,但我似乎无法让它工作。mysql + JOIN查询的问题

“销售”

---------------------- 
idcustomer | datecode 
---------------------- 
1   | 20120503 
1   | 20120503 
1   | 20120503 
2   | 20120503 
3   | 20120503 

我想知道谁是最大买家....在多少次客户从我这里买走的东西在especific天方面(是的,我用一些奇怪的格式日期我知道,请不要介意说)......,所以我做的:

SELECT idcustomer, COUNT(idcustomer) FROM sales WHERE datecode = 20120503 GROUP BY idcustomer ORDER BY COUNT(idcustomer) DESC 

,我也得到:

----------------------------- 
idcustomer | Count(idcustomer) 
----------------------------- 
1   | 3 
2   | 1 
3   | 1 

的问题是... SI NCE我也有表:

“客户”

---------------------- 
| name | id_customer | 
---------------------- 
Jess | 1 
Matt | 2 
Perry | 3 

及以下就是我想达到什么样的....怎么办呢?

--------------------------------------------- 
customer.name | idcustomer | Count(idcustomer) 
--------------------------------------------- 
Jess   | 1   | 3 
Matt   | 2   | 1 
Perry  | 3   | 1 
+0

按日期代码添加分组 –

回答

1
SELECT customer.name, idcustomer, COUNT(idcustomer) 
FROM sales 
JOIN customer 
ON sales.idcustomer = customer.id_customer 
WHERE datecode = 20120503 
GROUP BY idcustomer 
ORDER BY COUNT(idcustomer) DESC 

看到它联机工作:sqlfiddle

+0

感谢您的重播。喜欢sqlfiddle。 – Khul

0

你需要做这种方式 -

SELECT idcustomer, c.name, COUNT(idcustomer) 
FROM sales s inner join customer c on (s.idcoustomer=c.id_customer) 
WHERE datecode = 20120503 
GROUP BY idcustomer, c.name 
ORDER BY COUNT(idcustomer) DESC 
+0

感谢您的回复! – Khul

0

希望这将有助于::

Select cust_ref.idcustomer, cust_ref.COUNT(idcustomer), customer.name 
from 
(SELECT idcustomer, COUNT(idcustomer) FROM sales WHERE datecode = 20120503 
GROUP BY idcustomer) cust_ref 
inner join customer on (sales.idcustomer = customer.id_customer) 
ORDER BY COUNT(idcustomer) DESC 
0
SELECT 
    t1.name,t2.count_buy,t2.idcustomer 
    FROM customer as t1, 
(SELECT 
    idcustomer,COUNT(idcustomer) as count_buy 
     FROM `sales` 
     WHERE datecode = 20120503 
     GROUP BY idcustomer 
     ORDER BY COUNT(idcustomer) DESC) t2 
    WHERE 
    t1.idcustomer =t2.idcustomer 
+0

这种方法我以前没有见过。我将进一步调查。 TY – Khul