有没有一种方法可以不使用联接来回答这个问题?
编写一个查询,为每个客户X找到至少订购了一种与X共同产品的另一个客户Y。找到所有这样的客户对(X,Y),并针对每对找到重叠产品的数量。因此,查询应该有三列。按重叠产品的数量对结果进行排序。
问题使用https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all数据库。
使用联接,我可以这样回答问题:
O2.CustomerID AS Cust2,
COUNT(*) AS OverlappingProd
FROM (SELECT O.CustomerID, OD.ProductID
FROM Orders AS O
JOIN OrderDetails AS OD
ON OD.orderid = o.orderid) AS O1
JOIN(SELECT O.CustomerID, OD.ProductID
FROM Orders AS O
JOIN OrderDetails AS OD
ON OD.orderid = o.orderid) AS O2
ON O2.ProductID = O1.ProductID
AND O2.CustomerID > O1.CustomerID
GROUP BY
O1.CustomerID,
O2.CustomerID
ORDER BY COUNT(*) DESC;
有没有办法不使用连接函数来解决这个问题?谢谢你的时间和考虑。
我想不出一种没有任何连接的方法来完成这件事。您可以使用交叉连接
和exists
在SQL中表达这一点,因此下面的内容非常接近:
select c1.customerid, c2.customerid,
(select count(*)
from products p
where exists (select 1
from orderdetails od
where od.productid = p.productid and
exists (select 1
from orders o
where o.orderid = od.orderid and
o.customerid = c1.customerid
)
) and
exists (select 1
from orderdetails od
where od.productid = p.productid and
exists (select 1
from orders o
where o.orderid = od.orderid and
o.customerid = c2.customerid
)
)
) as num_products
from customers c1 cross join
customers c2
where c1.customerid < c2.customerid;
虽然这种语法将在许多数据库中起作用,但在MySQL中不支持嵌套的相关子句。因此,即使接受交叉连接
,这在MySQL中也不起作用。
join
似乎有必要的原因是要在结果集中获得两个独立的客户ID。