1


1 ...
LogEntryID*PrimaryKey*
Value
ThresholdID - - - 链接到应用于此日志条目的适当阈值。
...

表 2
...
ThresholdID*PrimaryKey*
阈值
...

所有字段都是整数。
“...”的东西表明这些表格包含的信息远不止这些。它们以这种方式设置是有原因的,我目前无法更改。

我需要编写一条 SQL 语句来从Table1中选择每条记录,其中该特定日志记录中的 Value 字段小于Table2的链接记录中的 Threshold 字段。

我对 SQL 很陌生,所以我知道这是一个基本问题。
如果有人能告诉我这个 SQL 语句的结构,将不胜感激。

4

5 回答 5

4
SELECT T1.*
  FROM Table1 T1
  JOIN Table2 T2 ON T2.ThresholdID = T1.ThresholdID
 WHERE T2.Threshold > T1.Value
于 2009-07-17T19:35:30.570 回答
1
SELECT * FROM Table1
JOIN Table2
ON table1.ThresholdID = table2.ThresholdID --(assuming table 2 holds the same value to link them together)
WHERE
value < thresholdvalue

'JOIN' 基于 'ON' 子句连接 2 个表(可以是多部分的,使用 'AND' 和 'OR')

如果表 2 中有 3 个条目共享 table1 的主键(一对多关联),您将在结果集中收到 3 行。

对于下表,例如:

Table 1:
Key     Value
1       Hi
2       Bye

Table 2:
Table1Key  2nd_word
1           You
1           fellow
1           friend
2           now

这个查询:

SELECT * FROM Table1 JOIN Table2 on table1.key = table2.table1key

得到这个结果集:

Key    Value    Table1Key   2nd_word
1      Hi        1          You
1      Hi        1          fellow
1      Hi        1          friend
2      Bye       2          now

请注意,JOIN 只会在第二张表中有匹配时返回结果,如果没有匹配则不会返回结果。您可以为此进行 LEFT JOIN(第二个表中的所有字段都将为 NULL)。

JOIN 也可以串在一起,使用前一个 JOIN 的结果代替原始表。

于 2009-07-17T19:34:40.900 回答
1
SELECT t1.*
FROM dbo.Table1 t1 INNER JOIN dbo.Table2 t2 ON t1.ThresholdID = t2.ThresholdID
WHERE t2.Threshold > t1.Value
于 2009-07-17T19:35:40.210 回答
1

SELECT * from table1 t1 join table2 t2 on (t1.thresholdId = t2.thresholdId) where t1.value < t2.threshold;

于 2009-07-17T19:35:45.657 回答
1
SELECT t1.LogEntryID, t1.Value, t1.ThresholdID
FROM Table1 t1 
INNER JOIN Table2 t2 ON t1.ThresholdID = t2.ThresholdID 
WHERE t1.Value < t2.threshold
于 2009-07-17T19:36:14.797 回答