【问题标题】:MySQL join Query for three tablesMySQL join 查询三个表
【发布时间】:2015-05-22 04:43:24
【问题描述】:

我有三张桌子:

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;

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

【问题讨论】:

  • asset_type_mst 中只有 5 个值?还是您希望这是动态的?
  • asset_type_mst中的值会多于5个,但会修复。

标签: mysql join


【解决方案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 小提琴here

首先声明一个fs 以使用来自asset_type_mst 的所有asset_type_name 组合动态sum(if) 语句。
然后使用将动态 sum(if) statment fs 连接到 normal group by statment 来准备一个statment。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    相关资源
    最近更新 更多