2017-07-28 72 views
0

我有一个表artefact_combosMySQL的:选择组合中的项目所需的数量所拥有的所有组合

id name       points study_time 
3 Climate Priority Oven   13333 13333 

和另一artefact_combo_items指定项目,使所需的那些项目的数量artefact_combo

id  artefact_combo_id thing_id number 
138  3     809   2 
139  3     798   3 
141  3     583   1 

接着的的第三表user_thing

SELECT * 
FROM `user_thing` 
WHERE (thing_id =809 
OR thing_id =798 
OR thing_id =583) WHERE user_id=4 
LIMIT 0 , 30 

id  user_id thing_id 
3229 4  583   
17756 4  583   

因此,在这种情况下,用户4具有> =所需的项目数583,但没有其他需要的项目数,所以我期待和空的结果。如果结果是:

id  user_id thing_id 
3229 4  583   
156  4  583   
17756 4  789 
17856 4  789 
67756 4  789 
122323 4  809 
434  4  809 

我想要一个结果集,如:

id name       points study_time 
3 Climate Priority Oven   13333 13333 

我试图构建一个MySQL查询,将得到的artefact_combos列表:某一特定user_id具有所需数量artefact_combo_itemsartefact_combos

我最近的最后4小时尝试是:

SELECT foo.thing_id, 
count(user_thing.id) 
FROM 
(SELECT 
    a.name, 
    c.id, 
    c.artefact_combo_id, 
    c.thing_id, 
    c.number 
FROM artefact_combo_items AS c 
    INNER JOIN user_thing AS b ON b.id = c.thing_id 
    INNER JOIN artefact_combos AS a ON a.id = c.artefact_combo_id 

ORDER BY a.name DESC) AS foo, user_thing WHERE user_thing.id = foo.thing_id 

我的道歉,如果这个问题太具体或严重解释;我可能比我准备啃咬的还要多。任何想法,提示或教导将非常感激。谢谢!

+0

你似乎对第三表没有主键,这可能使事情不相称难以 – Strawberry

+1

查询不符合您的架构。也许你可以使用这个网站http://sqlfiddle.com/创建一个最小的例子,并告诉我们,你期望得到什么结果 –

+0

@Strawberry谢谢 - 我试图改变这个问题,以更具体地说明我是什么实际上面对。 –

回答

0

我会查询没有丢失物品组合用户:

SELECT ac.* 
    , u.id user_id 
    FROM artefact_combos ac 
    JOIN (SELECT distinct user_id id 
      FROM user_thing 
     ) u 
    WHERE not exists(SELECT 1 
         FROM artefact_combo_items aci 
         LEFT JOIN (SELECT user_id 
             , thing_id 
             , count(1) cnt 
             FROM user_thing ut 
             GROUP BY user_id 
              , thing_id 
           ) ui 
          ON ui.thing_id = aci.thing_id 
         WHERE aci.artefact_combo_id = ac.id 
         AND ( ui.user_id is null 
          OR ( ui.user_id = u.id 
           and ui.cnt < aci.number 
           ) 
          ) 
       ) 
+0

嗨@Sal - 谢谢,这真的很棒,似乎正在得到我需要的东西。它比我希望运行查询要慢,但是3000个组合项目,8000个组合项目和每个用户大约7000个用户项目,我不确定我的预期!再次感谢您帮助解决这个问题。 –