【问题标题】:SQL using the except clause使用 except 子句的 SQL
【发布时间】:2019-03-05 08:43:11
【问题描述】:

我有 2 张桌子:

  • 表 1 有 4 列

    • column1 是我的 id
    • column2 是整数
    • column3 是日期
    • column4 是 varchar
  • 表 2 有 5 列

    • column1 是 id
    • column2 是整数
    • column3 是整数
    • column4 是 varchar
    • column5 是 varchar。

这是我目前的查询:

SELECT column2
FROM table1
WHERE column3 >= #today#
EXCEPT
SELECT column3
FROM table2
WHERE column2 = '2628'
ORDER BY table1.column2

当我显示我的结果时,它会显示我想要的信息,但我希望它显示 table1、column3…

这是我的输出:(我正在使用 ColdFusion)

cfoutput query="date"
School Day - #table1column2# br
/cfoutput

47
48
49
52
53
55

我希望它显示如下:

11/1/2018
11/2/2018
11/3/2018
11/6/2018
11/8/2018

我尝试过INNER JOIN table2 ON table1.column2 = table2.column3,但它似乎不起作用。
任何帮助将不胜感激。

【问题讨论】:

  • 能否让您的问题更具可读性
  • MySQL 不支持except 子句
  • 请将代码部分格式化为:code = code_lol.
  • 不清楚你想做什么。尝试清楚地说明一些示例数据的预期输出。

标签: mysql


【解决方案1】:

您必须使用except 还是not exists 可以使用?

如果我了解您想要 table1 中的所有记录 除了在 table1 column2 上匹配 table2 column3 的那些,其中 table2 的 column2 的值为 2628。

我在子查询中使用 1,因为那里返回的值并不重要。我们使用相关性将 t1 连接到 t2 并将 t2 的第 2 列限制为所需的值。

由于您要查找的数据在 table1 中,而 table2 中不需要任何内容​​;我倾向于将表 2 放在 where 子句中,因为它是您希望从表 1 中查看的数据的过滤器。如果您需要来自 table2 的数据,我可能会在这里使用左连接。

SELECT t1.column2, t1.column3
FROM table1 t1
WHERE t1.column3 >= #today# 
 and not exists (SELECT 1 
                FROM table2 t2
                WHERE  t1.column2 = t2.column3
                  and t2.column2 = '2628')
ORDER BY T1.column2

我不喜欢按列排序而不显示它,所以我把它留在了查询结果中。

Except 仅在您限制为 t1.column2 和 t2.column3 然后将其用作子查询从 t1 获取您想要的记录时才适用。这似乎是不需要的开销,因为 not exists 可以一步完成。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-21
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    相关资源
    最近更新 更多