【发布时间】:2015-08-30 08:34:36
【问题描述】:
我正在尝试连接两个表,但问题是收银员表可以与销售表中的 3 个字段连接,如果我只用一个字段连接两个表,我不想错过任何记录。我只想获得与收银员表一样多的行。我希望这是有道理的。这是我正在尝试做的一个例子。
SELECT cashiers.cashierId,cashiers.name,cashiers.age,
(SELECT
(SELECT SUM(amount) * .20 FROM sales WHERE cashierId1 = cashiers.cashierId) +
(SELECT SUM(amount) * .30 FROM sales WHERE cashierId2 = cashiers.cashierId) +
(SELECT SUM(amount) * .40 FROM sales WHERE cashierId3 = cashiers.cashierId)
) AS totalAmount
FROM cashiers
感谢大家的帮助。
【问题讨论】:
-
样本数据确实有助于阐明您在做什么。
-
您可以同时加入多个字段。
select * from table1 a inner join table2 b on a.column1 = b.column1 and a.col2 = b.col2 -
每笔销售是否只计入一名收银员?
-
许多cashierID 列很可能是糟糕的设计。 (因此导致查询和表谓词不必要的复杂性。)只需有一个 cashierID 列和记录行,其中“cashierID 确实销售 saleID AND ...”。我们必须猜测,直到您为当前表提供这样的谓词。例如“sale saleID ... AND(没有收银员这样做并且 cashierID1、cashierID2 和 cashierID3 为 NULL 或只有 cashierID1 做到了并且 cashierID2 和 cashierID3 为 NULL 或只有 cashierID1 和 cashierID2做到了,cashierID3 为 NULL 或只有 cashierID1 和 cashierID2 和 cashierIDI3* 做到了)并且 ..."。