1

我有两张桌子。一张桌子看起来像

ORDER_ID | SHOPPER_NAME | DATE
-------------------------------
001A     | Marianna     | 08/09/2012
002A     | Jason        | 80/08/2012

和另一个包含订单信息的表格

ORDER_ID | DATA_CODE   | DATA_VALUE
----------------------------------
001A     | MILK_MONEY  | 1.20
001A     | NUM_EGGS    | 22
002A     | TOTAL_SPENT | 32.43
001A     | TOTAL_SPENT | 42.13

我需要获取特定订单的几个数据代码。如何在一行中选择 SHOPPER_NAME、MILK_MONEY(DATA_VALUE,其中 DATA_CODE = 'MILK_MONEY')、TOTAL_SPENT 和 NUM_EGGS?我让它在我正在做 3 个连接的地方工作,比如

SELECT SHOPPER_NAME,
       MILK.DATA_VALUE,
       EGGS.DATA_VALUE,
       TOTAL.DATA_VALUE
FROM GROCERIES G
JOIN ORDER_INFO MILK ON MILK.ORDER_ID=G.ORDER_ID
JOIN ORDER_INFO EGGS ON EGGS.ORDER_ID=G.ORDER_ID
JOIN ORDER_INFO TOTAL ON TOTAL.ORDER_ID=G.ORDER_ID

然而,这开始看起来很难看,在同一张表上进行多个连接感觉不正确。有没有更有效的方法来做到这一点?

谢谢!

4

3 回答 3

0
SELECT SHOPPER_NAME,
       (select sum(DATA_VALUE) from ORDER_INFO where DATA_CODE  = 'MILK_MONEY' and ORDER_ID = G.ORDER_ID) as 'MilkValue'
       (select sum(DATA_VALUE) from ORDER_INFO where DATA_CODE  = 'NUM_EGGS' and ORDER_ID = G.ORDER_ID) as 'EggsValue'
       (select sum(DATA_VALUE) from ORDER_INFO where DATA_CODE  = 'TOTAL_SPENT' and ORDER_ID = G.ORDER_ID) as 'TotalSpentValue'
FROM GROCERIES G

用于subquerys获取每个总和(我不知道是否有多个列,或者是否有牛奶、鸡蛋等的总数;在这种情况下,删除sum's)每个总和将用于每个Order_Id

于 2012-08-09T19:49:02.710 回答
0

您可以在第二张表上使用一个数据透视表来对其进行一些非规范化,或者您可以通过对其进行一些非规范化来更改您的数据库架构。在堆栈溢出时查找 MySQL PIVOT 以获取更多示例,但类似以下内容:

SELECT * FROM 
(SELECT ORDER_ID, DATA_CODE, DATA_VALUE FROM tablename
PIVOT (sum(DATA_VALUE) FOR DATA_CODE IN ([MILK_MONEY], [NUM_EGGS], [TOTAL_SPENT])) pvt
于 2012-08-09T21:05:55.600 回答
-1
SELECT g.SHOPPER_NAME, oi.* from GROCERIES g JOIN ORDER_INFO oi on oi.ORDER_ID=G.ORDER_ID
于 2012-08-09T19:48:41.050 回答