我有一个生成以下输出的 SQL 脚本:
+------------+------------+--------------------+----------------------+---------------------+
| CUSTOMERID | TOTALCOUNT | VALIDWARRANTYCOUNT | EXPIREDWARRANTYCOUNT | LASTPURCHASED |
+------------+------------+--------------------+----------------------+---------------------+
| 1 | 5 | 5 | 0 | 2013-12-24 14:37:45 |
| 2 | 3 | 3 | 0 | 2013-12-24 14:37:45 |
| 3 | 6 | 6 | 0 | 2013-10-23 13:37:45 |
+------------+------------+--------------------+----------------------+---------------------+
我想在附加列中查看客户的公司名称。我有一个额外的表,customer id
但company name
我不知道如何扩展我的查询。所有尝试都会导致一个空表。
这是我的查询:
SELECT p2c.customerid
, (
SELECT COUNT(*)
FROM products2customers
WHERE customerid = p2c.customerid
) AS TotalCount
, (
SELECT COUNT(*)
FROM products2customers
WHERE customerid = p2c.customerid
AND date_add(from_unixtime(purchased), INTERVAL 5 YEAR) >= CURDATE()
) AS ValidWarrantyCount
, (
SELECT COUNT(*)
FROM products2customers
WHERE customerid = p2c.customerid
AND date_add(from_unixtime(purchased), INTERVAL 5 YEAR) < CURDATE()
) AS ExpiredWarrantyCount
, (
SELECT MAX( from_unixtime(purchased) )
FROM products2customers
WHERE customerid = p2c.customerid
) AS LastPurchased
FROM (
SELECT DISTINCT
p2c.customerid
FROM
products2customers p2c
INNER JOIN
products p
ON
p2c.customerid = p.id
) AS p2c
我用没有连接的普通查询做了一个 SQL Fiddle,我希望有人能给我一个提示。