0

我有 2 个表 - E & B,它们由 Breaktime 列链接。表 B 包含所有可用时间并将它们提供给表 E。如果表 E 未使用某个时间,则该时间的记录不再出现在表 E 中。我需要从 E 中选择 * 以获得使用的时间,但也需要不在E中但在B中的未使用时间并将它们标记为“未使用”。查询有很多参数,所以这里是简短的版本:

SELECT 
    e.BreakDate, b.Breaktime,
        (CASE WHEN...) to separate the times into categories
FROM
    event e, break b, *several more tables*
WHERE
    e.breakdate = b.breakdate
and e.breaktime = b.breaktime
and *linking additional tables*

我试过使用

WHERE NOT EXISTS (SELECT e.breaktime FROM E,B WHERE e.breaktime = b.breaktime) 

我试过使用

IF EXISTS (
    SELECT e.breaktime
    FROM E,B
    WHERE e.breaktime = b.breaktime
) THEN (
    SELECT b.breaktime
    FROM E,B
    where NOT EXISTS (
        SELECT *
        FROM E,B
        WHERE e.breaktime = b.breaktime
    )

提前致谢。

4

1 回答 1

0

考虑从B这样的选择:

SELECT ...
FROM B
    LEFT JOIN E ...

By performing the LEFT JOIN you'll get all rows from B and matching rows from E. Bear in mind that you will get more than one row of B values because they will exist for every matching row in E. The data might look like this:

B.Field1          B.Field2          E.Field1
============================================
1                 A                 NULL
2                 B                 Value 1
2                 B                 Value 2

The row where E.Field1 is NULL means there is no matching row in E for that B. By contrast, notice that the B fields seem duplicated. And at some level they are. But that's because there is more than one matching E for that B.

You can easily abstract this now, even just mentally, to where you could do some grouping and distinct manipulations of sub queries to ensure you only got what you wanted from E. Maybe you make an inner query like this:

SELECT ...
FROM E
WHERE E.field IN (
    SELECT e.field
    FROM B
        LEFT JOIN E ...
    GROUP BY ....
)

That's just an example.

于 2013-09-27T14:59:45.213 回答