使用JOIN和UNION组合来自不同表的记录

时间:2013-01-11 22:18:14

标签: mysql

我需要创建一个查询来组合来自两个表的数据,我想可能是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

非常感谢您提供的任何帮助!

3 个答案:

答案 0 :(得分:3)

这应该有效:

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) |

See it in action

答案 1 :(得分:1)

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

答案 2 :(得分:0)

select * 
from food f 
left join drink d on f.name = d.name 
where d.status = 'active' and f.status = 'active'