簡體   English   中英

使用JOIN和UNION組合來自不同表的記錄

[英]Combine records from differing tables using JOIN and UNION

我需要創建一個查詢來組合來自兩個表的數據,我想可能是JOIN和UNION的組合。

在這個例子中,我需要列出狀態為活動狀態的所有名稱,只需一次,將他們的葡萄酒,蘇打水,晚餐,甜點和水果首選項組合在一起,按名稱排序。

我不確定JOIN是否會起作用,因為名稱並不總是在兩個表中,並且UNION很棘手,因為它們沒有相同的列。 我已經嘗試使用空值來使UNION工作,但是這給了我每個名稱的重復行,而不是將它們分組為每個名稱一行。

DRINK
====================================
name         status   wine    soda
----------   ------   ------  ------
John Smith   active   red     cola
Mary Jones   active   white   lemonade
Tom Brown    old      red     fanta
Judy White   active   red     dr pepper
Sam Wing     old      red     cola

FOOD
=============================================
name         status   dinner  dessert  fruit
----------   ------   ------  ------   ------
John Smith   active   steak   muffin   apple
Mary Jones   active   fish    cake     kiwi
Walter Yu    active   pasta   cake     banana
Jim Adams    old      steak   candy    apple
Adam Sheers  active   pasta   candy    grapes

我需要查詢來生成這樣的結果 -

RESULT
==================================================================  
name         status    wine     soda       dinner  dessert  fruit
----------   ------    ------   ------     ------  ------   ------
Adam Sheers  active    -        -          pasta   candy    grapes
John Smith   active    red      cola       steak   muffin   apple
Judy White   active    red      dr pepper  -       -        -
Mary Jones   active    white    lemonade   fish    cake     kiwi
Walter Yu    active    -        -          pasta   cake     banana

非常感謝您對此的任何幫助!

這應該工作:

SELECT names.name, drink.wine, drink.soda, food.dinner, food.dessert, food.fruit
FROM
    (SELECT name FROM food WHERE status = 'active'
    UNION
    SELECT name FROM drink WHERE status = 'active') names
LEFT JOIN drink ON drink.name = names.name
LEFT JOIN food ON food.name = names.name

結果

|        NAME |   WINE |      SODA | DINNER | DESSERT |  FRUIT |
----------------------------------------------------------------
|  John Smith |    red |      cola |  steak |  muffin |  apple |
|  Mary Jones |  white |  lemonade |   fish |    cake |   kiwi |
|   Walter Yu | (null) |    (null) |  pasta |    cake | banana |
| Adam Sheers | (null) |    (null) |  pasta |   candy | grapes |
|  Judy White |    red | dr pepper | (null) |  (null) | (null) |

看到它在行動

SELECT name, status, MAX(wine) wine, MAX(soda) soda, MAX(dinner) dinner, MAX(dessert) dessert, MAX(fruit) fruit
FROM
  (
    SELECT name, status, wine, soda, NULL dinner, NULL dessert, NULL  fruit
    FROM DRINK WHERE status = 'active'
    UNION ALL
    SELECT name, status, NULL wine, NULL soda, dinner, dessert, fruit
    FROM FOOD WHERE status = 'active'
  ) R
  GROUP BY name, status
select * 
from food f 
left join drink d on f.name = d.name 
where d.status = 'active' and f.status = 'active'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM