MySQL连接查询三个表

时间:2015-03-19 06:17:51

标签: mysql join

我有三张桌子:

asset_details
------------------------------
asset_no    asset_type_id
------------------------------
AS1     id1
AS2     id2
AS3     id1
AS4     id3
AS5     id1
--------------------------------

asset_customer_mapping
--------------------------------
asset_no    customer_site_id
--------------------------------
AS1     site1
AS2     site1
AS3     site2
AS4     site4
AS5     site1

asset_type_mst
-------------------------------
asset_type_id   asset_type_name
-------------------------------
id1     Desktop
id2     Laptop
id3     Printer
id4     Plotter
id5     Router

现在我需要mysql的以下结果:

SiteName | Desktop | Laptop | Printer | Plotter | Router | Total
-----------------------------------------------------------------
site1   |    2     |  1     |    0    |    0    |    0    |  3
site2   |    1     |  0     |    0    |    0    |    0    |  1
site3   |    0     |  0     |    0    |    0    |    0    |  0
site4   |    0     |  0     |    1    |    0    |    0    |  1
site5   |    0     |  0     |    0    |    0    |    0    |  0
----------------------------------------------------------------
Total   |    3     |  1     |    1    |    0    |    0    |  5

我已经通过以下查询对customer_site_ids进行分组

select b.customer_site_id,count(*) from asset_details a,asset_customer_mapping b,asset_type_mst c
where a.asset_no=b.asset_no and a.asset_type_id=c.asset_type_id
group by b.customer_site_id;

但是我无法获得类型分离以获得所需的结果。任何帮助都非常感谢。感谢

1 个答案:

答案 0 :(得分:1)

set @fs='';

select @fs:=concat(@fs,'sum(if(asset_type_name=\'',asset_type_name,'\',1, 0)) as ', asset_type_name, ',')
    from (select distinct asset_type_name from asset_type_mst) A;

set @statq=concat('select ifnull(customer_site_id, \'total\') sitename,', @fs, 'count(1) as total',
              ' from asset_details d join asset_customer_mapping c on d.asset_no = c.asset_no',
              ' join asset_type_mst a on d.asset_type_id=a.asset_type_id',
              ' group by customer_site_id WITH ROLLUP');

prepare stmt from @statq;
execute stmt;

sql fiddle here

首先声明fs使用sum(if)中的所有asset_type_name组合动态asset_type_mst语句。
然后使用concat动态求和(if)语句fs按照法则对正常组进行准备。