【问题标题】:select rows with same ID and select remaining row without same ID选择具有相同 ID 的行并选择没有相同 ID 的剩余行
【发布时间】:2011-12-09 14:51:40
【问题描述】:

我需要先选择具有公共 ID 的行,然后选择没有公共 ID 的其余行(不重复。)

这是我目前所拥有的:

SELECT DISTINCT a.cars,b.wheels,c.glass
FROM table auto a, tires b, window c
WHERE a.ID = b.ID AND c.ID = a.ID
????AND/OR a.ID <> b.ID????

自动

id cars
1   data
2   data
3   data
4   data

轮胎

id wheels
1   data
2   data
5   data  <-- ID different from table 'Auto' but still want to select it
9   data  <-- ID different from table 'Auto' but still want to select it
200 data  <-- ID different from table 'Auto' but still want to select it

窗口

id glass
1  data
2  data
3  data
4  data

【问题讨论】:

  • 您需要向我们展示一些表结构和示例数据,并更清楚地解释您要在这里实现的目标......

标签: sql-server tsql select


【解决方案1】:

使用 LEFT JOIN,而不是通过 WHERE 子句获得的隐式 INNER JOIN,将从 auto 表中返回匹配和不匹配的行。

SELECT DISTINCT a.cars, b.wheels, c.glass
    FROM auto a
        LEFT JOIN tires b
            ON a.id = b.id
        LEFT JOIN window c
            ON a.id = c.id
    ORDER BY a.cars, b.wheels, c.glass

【讨论】:

  • 天哪——你怎么能弄清楚这个问题到底是关于什么的!?!?我很欣赏你的才华.... :-)
  • @marc_s:多年将用户需求文档转化为功能代码的实践。 :-)
  • 正如 Joe 所展示的,明确声明您的 JOIN 总是一个好主意。这有助于防止任何歧义并保护您免于进行笛卡尔连接(如果您弄乱了 WHERE 子句)。
猜你喜欢
  • 2023-01-11
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
  • 2020-12-20
  • 2020-10-05
  • 2020-01-06
  • 2013-11-04
  • 1970-01-01
相关资源
最近更新 更多