如何连接多个条件,返回两个条件的所有组合

时间:2012-10-30 00:13:32

标签: sql sql-server join

我愿意打赌这是一个非常简单的答案,因为我是SQL的菜鸟。

表1列第1列(标准1)第2列(标准2)第3列(指标1)

表2列第1列(标准1)第2列(标准2)第3列(特定于table2.criteria2的度量标准2)

表格中的每个标准1可以有1到5个标准值2。

当我在这里使用join语句时(假设我在此之前将表1标识为One):

Select WeddingTable, TableSeat, TableSeatID, Name, Two.Meal
FROM table1 as One
inner join table2 as Two
on One.WeddingTable = Two.WeddingTable and One.TableSeat = Two.TableSeat

我只得到其中一个标准1 /标准2组合,即使我知道有3或4的事实。我如何获得所有组合?

在有婚礼的情况下,表1基本上是座位表,表2是每个桌子/座位选择的用餐选项。表1具有方便的TableSeatID,但表2没有可比较的ID。

示例数据:

enter image description here

结果需要显示所有4条线,分别是WeddingTable 001的3个席位和WeddingTable 002的1个席位。

期望的结果:

enter image description here

4 个答案:

答案 0 :(得分:57)

select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)

答案 1 :(得分:4)

SELECT  aa.*,
        bb.meal
FROM    table1 aa
        INNER JOIN table2 bb
            ON aa.tableseat = bb.tableseat AND
                aa.weddingtable = bb.weddingtable
        INNER JOIN
        (
            SELECT  a.tableSeat
            FROM    table1 a
                    INNER JOIN table2 b
                        ON a.tableseat = b.tableseat AND
                            a.weddingtable = b.weddingtable
            WHERE b.meal IN ('chicken', 'steak')
            GROUP by a.tableSeat
            HAVING COUNT(DISTINCT b.Meal) = 2
        ) c ON aa.tableseat = c.tableSeat

答案 2 :(得分:1)

create table a1
(weddingTable INT(3),
 tableSeat INT(3),
 tableSeatID INT(6),
 Name varchar(10));

insert into a1
 (weddingTable, tableSeat, tableSeatID, Name)
 values (001,001,001001,'Bob'),
 (001,002,001002,'Joe'),
 (001,003,001003,'Dan'),
 (002,001,002001,'Mark');

create table a2
 (weddingTable int(3),
 tableSeat int(3),
 Meal varchar(10));

insert into a2
(weddingTable, tableSeat, Meal)
values 
(001,001,'Chicken'),
(001,002,'Steak'),
(001,003,'Salmon'),
(002,001,'Steak');

select x.*, y.Meal

from a1 as x
JOIN a2 as y ON (x.weddingTable = y.weddingTable) AND (x.tableSeat = y. tableSeat);

答案 3 :(得分:0)

听起来您想列出所有指标?

SELECT Criteria1, Criteria2, Metric1 As Metric
FROM Table1
UNION ALL
SELECT Criteria1, Criteria2, Metric2 As Metric
FROM Table2
ORDER BY 1, 2

如果您只想要一个Criteria1 + Criteria2组合,请将它们分组:

SELECT Criteria1, Criteia2, SUM(Metric) AS Metric
FROM (
    SELECT Criteria1, Criteria2, Metric1 As Metric
    FROM Table1
    UNION ALL
    SELECT Criteria1, Criteria2, Metric2 As Metric
    FROM Table2
)
ORDER BY Criteria1, Criteria2