74

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

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

表 2 具有第 1 列(标准 1)第 2 列(标准 2)第 3 列(特定于 table2.criteria2 的指标 2)

对于表格上的每个标准 1,标准 2 的值可以是 1 - 5 个。

当我在这里使用 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

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

以有一场婚礼为例,table 1 基本上是座位表,table 2 是每个桌子/座位选择的用餐选项。表 1 具有方便的 TableSeatID,但表 2 没有可比较的 ID。

样本数据:

在此处输入图像描述

结果需要显示所有 4 行,即 WeddingTable 001 的所有 3 个座位和 WeddingTable 002 的一个座位。

期望的结果:

在此处输入图像描述

4

4 回答 4

108
select one.*, two.meal
from table1 as one
left join table2 as two
on (one.weddingtable = two.weddingtable and one.tableseat = two.tableseat)
于 2014-05-28T02:35:27.653 回答
5
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
于 2012-10-30T00:49:01.340 回答
2
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);
于 2014-04-04T23:35:00.043 回答
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
于 2012-10-30T00:30:03.290 回答