结合3个不同的查询

时间:2017-01-01 22:23:48

标签: mysql ssrs-2008

我正在查询MySQL数据库以获取SSRS 2008中的报告,使用以下内容连接两个不同的查询我没有问题...

SELECT a.arrivalDate, a.order_item_id, b.roomType
FROM 
(select order_item_id, meta_value as arrivalDate from `wp_woocommerce_order_itemmeta` WHERE `meta_key` LIKE 'Arrival Date') as a, 
(select order_item_id, meta_value as roomType from `wp_woocommerce_order_itemmeta` WHERE `meta_key` LIKE 'type-of-room') as b
WHERE a.order_item_id = b.order_item_id

...但是当我尝试添加第三个时,它会对我的WHERE子句产生问题,但我可以发誓我曾经这样做过:

SELECT a.arrivalDate, a.order_item_id, b.roomType, c.retreatDate
FROM 
(select order_item_id, meta_value as arrivalDate from `wp_woocommerce_order_itemmeta` WHERE `meta_key` LIKE 'Arrival Date') as a, 
(select order_item_id, meta_value as roomType from `wp_woocommerce_order_itemmeta` WHERE `meta_key` LIKE 'type-of-room') as b,
(select order_item_id, meta_value as retreatDate from `wp_woocommerce_order_itemmeta` WHERE `meta_key` LIKE 'retreat-date') as c,
WHERE a.order_item_id = b.order_item_id AND a.order_item_id = c.order_item_id

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

没关系,明白了!我以为这是我最初尝试的,但我一定有错字。希望我的错误将有助于其他人在未来遇到这个问题:

SELECT a.arrivalDate, a.order_item_id, b.roomType, c.retreatDate
FROM 
(select order_item_id, meta_value as arrivalDate from `wp_woocommerce_order_itemmeta` WHERE `meta_key` LIKE 'Arrival Date') as a, 
(select order_item_id, meta_value as roomType from `wp_woocommerce_order_itemmeta` WHERE `meta_key` LIKE 'type-of-room') as b,
(select order_item_id, meta_value as retreatDate from `wp_woocommerce_order_itemmeta` WHERE `meta_key` LIKE 'retreat-date') as c
where a.order_item_id = b.order_item_id AND b.order_item_id = c.order_item_id

答案 1 :(得分:0)

我会坚持使用任何一种常规解决方案 - 首先是(IMO)更容易阅读。第二个通常更快......

查询1

SELECT order_item_id
     , MAX(CASE WHEN meta_key = 'Arrival Date' THEN meta_value END) arrivalDate
     , MAX(CASE WHEN meta_key = 'type-of-room' THEN meta_value END) roomType
     , MAX(CASE WHEN meta_key = 'retreat-date' THEN meta_value END) retreatDate
  FROM wp_woocommerce_order_itemmeta 
 GROUP
    BY order_item_id

查询2

SELECT DISTINCT x.order_item_id
              , arrival.meta_value arrivalDate
              , room.meta_value roomType
              , date.meta_value retreatDate
           FROM wp_woocommerce_order_itemmeta x
           LEFT
           JOIN wp_woocommerce_order_itemmeta arrival
             ON arrival.order_item_id = x.order_item_id
            AND arrival.meta_key = 'Arrival Date' 
           LEFT
           JOIN wp_woocommerce_order_itemmeta room
             ON room.order_item_id = x.order_item_id
            AND room.meta_key = 'type-of-room' 
           LEFT
           JOIN wp_woocommerce_order_itemmeta date
             ON date.order_item_id = x.order_item_id;