MySQL为600 000条记录选择查询优化

时间:2013-01-27 12:15:09

标签: mysql

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

SELECT * FROM products

然后为每个产品我提取代码和类别:

SELECT * FROM categories WHERE productid=[productid]

SELECT * FROM codes WHERE productid=[productid]

感谢您的任何建议

1 个答案:

答案 0 :(得分: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