SQL查询三个表

时间:2012-07-31 06:38:06

标签: sql

TABLE1

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

TABLE2

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

表3

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

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

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

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

1 个答案:

答案 0 :(得分:1)

您使用的是RDBMS,MS SQL Server,MySQL,Oracle?对handle tSQLcreate queriesuse 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