总结了mysql中的许多表

时间:2013-01-24 09:32:15

标签: mysql sql select

我有一个任务是制作一个包含数千条记录的数千个其他表的汇总表。摘要表应包含:

  1. 非冗余的“记录”列表;
  2. 包含该“记录”的表格数量
  3. 包含该“记录”的表的名称
  4. 示例是:

    Table_1
    nameA
    nameB
    nameC
    
    Table_2
    nameB
    nameC
    nameD
    
    Table_3
    nameC
    nameD
    nameE
    

    结果应该是这样的

    Record_name  Number  Table_names
    nameA        1       Table_1
    nameB        2       Table_1, Table_2
    nameC        3       Table_1, Table_2, Table_3
    nameD        2       Table_2, Table_3
    nameE        1       Table_3
    

    也许这不是一件复杂的事情,但是,因为我对mysql很新,所以我希望得到你们的一些建议和帮助!

1 个答案:

答案 0 :(得分:3)

SELECT  col1 as `Record Number`, 
        COUNT(*) as `Number`, 
        GROUP_CONCAT(_name) as `table name`
FROM
(
    SELECT col1, 'table_1' as _name FROM table_1
    UNION ALL
    SELECT col1, 'table_2' as _name FROM table_2
    UNION ALL
    SELECT col1, 'table_3' as _name FROM table_3
) a
GROUP BY col1