-2

表格1

ID    |     DATE             Ordered
 a    |   10-06-2012    |      1
 b    |   07-07-2012    |      1
 c    |   10-06-2012    |      0

表2

ID    |    OrdersID
 a    |     001
 b    |     002
 c    |     003

表3

OrdersID   |  Items  |  
 001       |   5    |  
 002       |   3    |  
 003       |   7    | 

我有三个表,我想在 TABLE1 中搜索 DATE,例如 10-06-2012 和 Ordered,例如 1 并返回 ID 'a'。

在 Table2 中,我希望它使用 Table1 的结果来获取 OrdersID

在 Table3 中,我希望它使用 Tables2 的结果来返回 Items ID 在两个表中都很常见。

4

1 回答 1

1

您使用的是哪种 RDBMS,MS SQL Server、MySQL、Oracle?对如何处理 tSQL创建查询使用 Joins等进行一些研究不会对您造成伤害。

如果您使用的是 MS SQL Server,这里是使用您提供的数据可以做什么的示例。请注意,嵌套查询可能非常慢,请检查您的索引、主键等。

--get from Table1 Id's filtering by date and Ordered fields
SELECT t1.Id
  FROM Table1 t1 JOIN Table2 t2
 WHERE t1.[Date] = '10062012 00:00:00'
   AND t1.Ordered = 1

--get from Table2 OrderedID filtered by previous query
SELECT t2.OredersID
  FROM Table2 t2
 WHERE t2.ID IN (SELECT t1.Id
                   FROM Table1 t1 JOIN Table2 t2
                  WHERE t1.[Date] = '10062012 00:00:00'
                    AND t1.Ordered = 1
                 )

--get from Table3 Items filtered by previous query
SELECT t3.Items
  FROM Table3 t3
 WHERE t3.OrdersID IN (SELECT t2.OrdersID
                         FROM Table2 t2
                        WHERE t2.ID IN (SELECT t1.Id
                                          FROM Table1 t1 JOIN Table2 t2
                                         WHERE t1.[Date] = '10062012 00:00:00'
                                           AND t1.Ordered = 1
                                        )
                      )

--Using JOINS, not sure if this is 100% correct
--get from Table3
SELECT t3.Items
  FROM Table3 t3
      JOIN Table2 t2 ON t3.OrdersID = t2.OrdersID
      JOIN Table1 t1 ON t2.ID = t1.ID
 WHERE t1.[Date] = '10062012 00:00:00'
   AND t1.Ordered = 1
于 2012-07-31T07:28:47.967 回答