使用依赖于MySQL中其他5个表的数据填充表

时间:2015-06-24 08:26:38

标签: mysql

我想用MySQL(My)SQL语句填充MySQL中的关系表。问题,为什么我现在正在坚持,我必须根据条件填写依赖于其他表的数据。我从来没有做过很多条件编程和循环内部的sql和我现在尝试的每个部分,使它以某种方式工作失败惨。我可能希望稍后将结果存储为存储过程,但是现在一个工作语句将不仅仅是令人满意。

表格设置:

我有5个数据表,我需要用关系数据填充第六个表。表结构如下所示:

table setup

现在我想只使用带有以下规则的sql(MySQL)来填写CategoryProducts的数据(伪代码)

foreach category-id:
  if allTags is true then
    fetch each product-id that has all tags that the category has
  else
    fetch each product-id that has at least one tag that the category has
  fi

  insert each product-id matching into CategoryProducts
end foreach

说实话,我不知道如何实现这一点,只使用普通的SQL。我通常会通过代码实现这一点,但这次我不能这样做。我想将此作为我们的一个外部服务器的安装脚本的一部分,但在安装例程的这一部分中,我只能执行SQL语句。

编辑:在表格设置图片中删除了丑陋的鼠标光标。

1 个答案:

答案 0 :(得分:1)

我认为你可以使用'简单'INSERT ... SOLECT:

来做到这一点
insert into CategoryProducts(cID, pID)
select
  -- The field list in `select` should match the list in the `insert into` clause.
  x.cID,
  x.pID
from
  -- Inner select returns all possible combinations, yet unfiltered by the
  -- conditions you specified, and returns the number of tags 
  -- for each product, each catagory, and the number of tags they share. 
  -- If SharedTagCount = cTagCount, it means that the product has all the tags 
  -- of the category (not necessarily the other way around).
  (select
    p.ID as pID,
    c.ID as cID,
    c.allTags,
    (select count(*) from ProductTags pt where pt.pID = p.ID) as pTagCount,
    (select count(*) from CategoryTags ct where ct.cID = c.ID) as cTagCount,
    (select
      count(*)
    from
      ProductTags pt
      inner join CategoryTags ct on ct.tCode = pt.tCode
    where
      pt.pID = p.ID and
      ct.cID = c.ID) as SharedTagCount
  from
    Product p
    cross join Categories c) x
where
  -- Outer select filters. 
  -- if SharedTagCount = cTagCount, it means that the product has all 
  -- the tags of the category.
  ( x.AllTags and
    x.cTagCount = x.SharedTagCount) or
  -- if SharedTagCount > 0, it means the product has at least one tag of the category.
  ( (not x.AllTags) and
    x.SharedTagCount > 0)