试图在另一个查询中使用查询结果......可能吗?

时间:2015-07-04 09:19:16

标签: mysql select join

orders_total ,其数据如下:

+-----------------+-----------+-----------+---------+-------------+
| orders_total_id | orders_id |   title   |  value  |    class    |
+-----------------+-----------+-----------+---------+-------------+
|               1 |         1 | Sub-total | 34.0000 | ot_subtotal |
|               2 |         1 | Tax       | 2.38    | ot_tax      |
|               3 |         2 | Sub-total | 12.0000 | ot_subtotal |
|               4 |         2 | Tax       | 0.60    | ot_tax      |
+-----------------+-----------+-----------+---------+-------------+

订单包含如下数据:

+-----------+----------+
| orders_id | currency |
+-----------+----------+
|         1 | USD      |
|         2 | CAD      |
+-----------+----------+

我想看看:

+-----------+----------+-----------+-------+
| orders_id | currency |  subtotal |  tax  |
+-----------+----------+-----------+-------+
|         1 | USD      | 34.0000   | 2.38  |
|         2 | CAD      | 12.0000   | 0.60  |
+-----------+----------+-----------+-------+

我想获取两个值(其中class =“ot_subtotal”)并将它们插入到我的select表中。但我似乎无法弄清楚如何在没有mysql choking的情况下查询另一个查询中的一个表。我已经阅读了很多关于此的问题/答案,但它们都有一些细节让我失望。我想我需要一个具体的例子来继续前进。

++ ++ EDIT 很抱歉,我过度简化了问题,并没有最终提出我想要的问题。我已经调整过了。我遇到的麻烦是将BOTH类分成一个输出。

4 个答案:

答案 0 :(得分:2)

如果您只关心为ot_subtotalot_tax生成数据透视表,那么以下内容应该可以解决问题

select
o.orders_id,
o.currency,
max(case when ot.class = 'ot_subtotal' then value end) as subtotal,
max(case when ot.class = 'ot_tax' then value end) as tax
from orders o
join orders_total ot on ot.orders_id = o.orders_id
group by o.orders_id

答案 1 :(得分:0)

您可以将两个表的内部联接用作:

Select o1.orders_id, o2.currency, o1.value from 
orders_total o1 inner join orders o2 on o1.orders_id = o2.orders_id 
where o1.class = "ot_subtotal"

答案 2 :(得分:0)

您可以加入draggable列:

orders_id

答案 3 :(得分:0)

试试这个,

INSERT INTO `new_table`(`orders_id`, `currency`, `value`) 
SELECT o.orders_id,o.currency,ot.value FROM `orders` o 
left join orders_total ot on o.orders_id = ot.orders_id   WHERE ot.class = 'ot_subtotal'