2

我需要从数据库中的所有产品(大约 600 000)生成 XML 文件。问题是我需要将每个产品的类别和代码放入该文件中。有些产品有 30 个类别和 10 个代码,这真的很痛苦。是否有可能以某种方式在单个有效查询中进行此操作,或者您能否给我一个提示如何改进我当前的解决方案:

SELECT * FROM products

然后对于我获取代码和类别的每个产品:

SELECT * FROM categories WHERE productid=[productid]

SELECT * FROM codes WHERE productid=[productid]

感谢您的任何建议

4

1 回答 1

0

也许你可以玩GROUP_CONCAThttp ://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

SELECT
  products.*,
  all_prod_categories.*
  all_prod_codes.*

FROM products

INNER JOIN
  (SELECT
     -- Who guarantees that all fields will be concated in the same order?
     -- Nobody :)
     GROUP_CONCAT( categories.id            ) AS all_prod_cat_ids,
     GROUP_CONCAT( categories.category_name ) AS all_prod_cat_names,
     ...
   FROM     categories
   GROUP BY categories.productid
  ) AS all_prod_categories ON categories.productid = products.id

INNER JOIN
  (SELECT
     GROUP_CONCAT( codes.id        ) AS all_prod_code_ids,
     GROUP_CONCAT( codes.code_name ) AS all_prod_code_names,
     ...
   FROM     codes
   GROUP BY codes.productid
  ) AS all_prod_codes ON codes.productid = products.id
于 2013-01-27T12:30:33.463 回答