如何获得未下订单产品的女性用户总数、男性用户总数以及(男性和女性用户的总和)。结果应如下所示:
total male | total female | total
---------------------------------------
31 | 24 | 55
---------------------------------------
fiddle 帮助http://sqlfiddle.com/#!9/3a0e30/36
之前的代码:
select p.*,
(select count(*)
from users u
where u.uid not in (select o.uid from orders o where o.productid = p.productid) and
u.gender = 'Male'
) as NumMales,
(select count(*)
from users u
where u.uid not in (select o.uid from orders o where o.productid = p.productid) and
u.gender = 'Female'
) as NumFemales
来自产品p;
最佳答案
抱歉,我一开始没理解你的问题,我以为你是在尝试计算用户数量,结果发现你是在尝试计算每个尚未下单的人可能购买的产品订单。
SELECT SUM(CASE WHEN gender = 'Male' THEN 1
ELSE 0
END) as Male,
SUM(CASE WHEN gender = 'Female' THEN 1
ELSE 0
END) as Female,
COUNT(1) as Total
FROM Users U INNER JOIN Products P
LEFT JOIN Orders O ON O.uid = U.uid AND P.productid = O.productid
WHERE O.uid IS NULL
sqlfiddle 此查询返回与之前的查询相同的结果,但不使用 IN 子句,因此可能会更快。
SELECT P.productid,P.productname,P.productdescription,
SUM(CASE WHEN gender = 'Male' THEN 1
ELSE 0
END) as Male,
SUM(CASE WHEN gender = 'Female' THEN 1
ELSE 0
END) as Female,
COUNT(1) as Total
FROM Users U INNER JOIN Products P
LEFT JOIN Orders O ON O.uid = U.uid AND P.productid = O.productid
WHERE O.uid IS NULL
GROUP BY P.productid,P.productname,P.productdescription
关于mysql - 获取未下订单产品的男性用户总数和女性用户总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36524728/