MySQL选择所有匹配X的人,然后选择每个人家中的所有人

时间:2014-01-25 15:50:18

标签: mysql

我需要查询两个表来打印列表 - PURCHASE HISTORYPEOPLE

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

2 个答案:

答案 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