【问题标题】:select from multiple tables, when one is never used从多个表中选择,当一个从不使用时
【发布时间】:2013-02-18 21:09:20
【问题描述】:

我用示例表改进了我的问题以便更好地理解

我有 3 个包含以下行的表:

TABLE1 t1                 TABLE t2              TABLE t3

ID   NAME    OBS          ID   HW_VER           ID   SERIAL
-----------------         -----------           ------------
1  | Name1 | Obs1         1  | HWVer1           5  | Serial5
2  | Name2 | Obs2         2  | HWVer2           6  | Serial6
3  | Name3 | Obs3         3  | HWVer3           7  | Serial7
4  | Name4 | Obs4
5  | Name5 | Obs5
6  | Name6 | Obs6
7  | Name7 | Obs7

现在,我想在满足 2 个条件时选择 id、name 和 obs:

  1. id 存在于 t2 或 t3 中(从不在两者中);
  2. 它指的是 t2 或 t3 属性(例如 t2.HW_VER='HWVER1'),从不在两者上

我做了这样的事情,但是错了:

SELECT DISTINCT t1.id, t1.name, t1.obs
FROM table1 t1, table2 t2, table3 t3
WHERE t1.id IN (t2.id, t3.id) AND t3.serial='Serial6';

我不能为此使用联合、外部表或视图。 如果有其他问题,请告诉我。

非常感谢您的回答,非常感谢您的宝贵时间..

【问题讨论】:

  • 问题是,你要数什么?
  • 请发布具有所需输出的示例数据——您的问题有点不清楚。
  • 如果不了解您的架构,您的问题很难形象化。但是您的 where 子句实际上是 OR。尝试将其设为 AND:其中 t1.id=t2.id AND t1.id=t3.id。
  • 谷歌搜索“where 子句中的案例构造”会让你开始。详细信息可能取决于您使用的数据库软件。你没有指定它。

标签: sql multiple-tables


【解决方案1】:

您需要从 T2 或 T3 中进行选择,但不能同时选择两者?我想你想要这样的东西

select count(*)
from t1
where exists (
    select 'x'
    from t2 
    where MyPrimaryKey_Name = 'random_name'
    and t2.id = t1.id
)
or exists (
    select 'x'
    from t3 
    where MyPrimaryKey_Name = 'random_name'
    and t3.id = t1.id
)

【讨论】:

    猜你喜欢
    • 2012-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    相关资源
    最近更新 更多