[英]MySQL join Query for three tables
我有三個表:
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;
但是我無法按類型進行分隔以獲得所需的結果。 非常感謝您的幫助。 謝謝
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 在這里擺弄
首先聲明一個fs
的動態結合sum(if)
使用所有語句asset_type_name
從asset_type_mst
。
然后使用動態總和(if)語句fs
與正常的逐組語句建立聯系。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.