日期:2014-05-16  浏览次数:20838 次

Mysql多对多查询、列合并
表信息
  • 资源表 synsource                                                 199824       rows
  • 产品表 tab_product_detail                                  108              rows
  • 资源与产品多对多的关联表 tab_r_sourmach  1,113,866   rows
以上表均采用MyISAM引擎.

连接测试
   因 为方便用户进行更好的资源的搜索,所以需要将资源数据全部建立索引至Lucene中,希望在Lucene中存储的Document为:
sourceNamefileNamesubjectgradeproducts
英语学生用书第十一册外研新标准.nwe英语小学NP7000 NP6000 NP2300
英语学生用书第十二册外研新标准2.nwe英语小学NP2300

以上前四个字段是属于 synsource表中,而 products 属于 tab_product_detail 表,它们之间的关系由tab_r_sourmach进行中间关联。
一开始想到的是直接使用以下SQL:
select s1.sourid, s1.sourcename , t.product_name from synsource s1 
  left join tab_r_sourmach c 
    on s1.sourid=c.sourid
      left join tab_product_detail t 
        on c.product_id = t.product_id where s1.sourceid=1

5 rows in set (0.45 sec)
sourid sourcename        subjectname product_name
      1 小六上Module07    英语        ND520       
      1 小六上Module07    英语        NP560T      
      1 小六上Module07    英语        NP560+      
      1 小六上Module07    英语        NP360+      

对于以上SQL的结果重复数据的合并处理考虑采用了 GROUP_CONCAT
select s1.*, GROUP_CONCAT(t.product_name SEPARATOR ' ') as product_name
  from tab_synsource s1 
    left join tab_r_sourmach c
      on s1.sourid=c.sourid
        left join tab_product_detail t 
              on c.product_id = t.product_id where s1.sourceid=1

1 row in set (0.31 sec)
sourid sourcename        subjectname product_name 
1 小六上Module07    英语        ND520 NTV518 NP560T NP560+ NP360+

看上去似乎能够满足需求,但是以上只是针对单条数据进行查询,对于数据的批量索引建立的话肯定是直接 limit 500之类的操作。于是去掉以上where加上 limit 10执行之后,半天都执行不出来,估计它先会全部数据连接查询之后再去 limit。
于是先测试一下直接(tab_r_sourmach, tab_product_detail)两表关联看看效率如何:
select c.sourid
from tab_r_sourmach c left join tab_product_detail t 
on  c.product_id = t.product_id  
group  by c.sourid limit 500;

以上语句用时:(5.65 sec)

再加上GROUP_CONCAT试试:
select c.sourid, GROUP_CONCAT(t.product_name SEPARATOR ' ') as product