我需要查询两个表来打印列表 - PURCHASE HISTORY
和PEOPLE
PURCHASE HISTORY
----------------
purchase_txnid...purchase_date...purchase_userid...purchase_productid
PEOPLE
------
people_householdid...people_userid...people_street...people_city...people_state...(etc)
我需要让所有人householdid
让某人购买productid = "X"
(基本上是SOMEONE
已购买产品的所有人的清单,然后显示他们的每次购买历史。
PURCHASE HISTORY
有七种不同的产品和320,000
条记录。
现在,我正在查询所有人,RIGHT JOIN
购买历史记录以选择购买"X"
的人,然后遍历结果,并在每个结果中查询{{1}这个家庭中的每个人以及他们的每个购买历史。由于有SELECT
人和45,000
次购买,因此速度非常慢。
关于如何将其合并为单个查询或优化的任何想法?
以下是查询:
320,000
答案 0 :(得分:1)
SELECT DISTINCT peopleB.userid, peopleB.* FROM purchase
JOIN people AS peopleA ON peopleA.people_userid = purchase_userid
JOIN people AS peopleB ON peopleB.people_householdid = peopleA.householdid
WHERE purchase.purchase_productid = "X"
您可以通过向表中添加这些索引来加速此查询:
CREATE INDEX productid ON purchase (purchase_productid)
CREATE INDEX householdid ON people (people_householdid)
我认为people_userid
已经是people
中的主要密钥,否则您应该将其设为唯一:
CREATE UNIQUE INDEX userid ON people (people_userid)
编辑 - 您要求提供完整的购买历史记录:
SELECT peopleB.*, phB.* FROM purchase_history AS phA
JOIN people AS peopleA ON peopleA.people_userid = phA.purchase_userid
JOIN people AS peopleB ON peopleB.people_householdid = peopleA.householdid
LEFT JOIN purchase_history AS phB ON phB.purchase_userid = peopleB.userID
GROUP BY peopleB.id, phB.purchase_txnid
WHERE purchase.purchase_productid = "X"
请注意,每次购买时,这都会为人们提供一次数据。
此外,我不知道该查询是否真的按照我想要的方式运行,或者它的速度有多快/慢。您也可以尝试倒转GROUP BY
行中的列,看看是否更快。
答案 1 :(得分:0)
您可以使用子查询和join
:
select p.*
from people p join
(select distinct p.people_householdid
from PurchaseHistory ph join
People p
on ph.purchase_userid = p.people_userid
where ph.purchase_productid = 'X'
) ph
on ph.people_userid = p.people_userid;
编辑:
如果您想标记进行购买的成员:
select p.*,
max(p.people_userid = ph.people_userid) as IsPurchaser
from people p join
(select p.people_householdid, p.people_userid
from PurchaseHistory ph join
People p
on ph.purchase_userid = p.people_userid
where ph.purchase_productid = 'X'
) ph
on ph.people_userid = p.people_userid
group by p.people_userid