-1

我有三张桌子。

Table1(Table1Id, Field1, Field2)
Table2(Table2Id, Table1Id, AuditDate, Field1, Field2)
Table3(Table3Id, Table1Id, AuditDate, Field1, Field2)

我想做的是选择 Table1 中的所有记录和字段,查看 Table2 和 Table3 以查找匹配的 Table1Id,然后从 Table3 中选择具有最新 AuditDate 的记录。我觉得我需要进行这样的查询。

SELECT DISTINCT Table1.Table1Id, Table1.Field1, Table1.Field2,
               Table2.Field1, Table2.Field2,
               Table3.Field1, Table3.Field2
FROM (Table1 
INNER JOIN Table2 ON Table1.Table1Id = Table2.Table2Id)
INNER JOIN Table3 ON Table1.Table1Id = Table3.Table3Id
WHERE Table3.AuditDate =
    (SELECT MAX(AuditDate) FROM Table3
     WHERE Table1.Table1Id = Table3.Table3Id)

这个半有效。例如,如果 Table3 中没有任何与 Table1 相关的记录,则不会返回任何内容。我需要确保为 Table1 中的每条记录创建一条记录。

4

4 回答 4

1

它应该是这样的查询:

SELECT t1.field1..t1.fieldN, t2.field1 ... t2.fieldN, t3.field1 ... t3.fieldN
FROM table1 AS t1
JOIN table2 AS t2 ON t1.id=t2.id
JOIN table3 AS t3 ON t2.id=t3.id
于 2012-12-17T14:10:27.257 回答
0

听起来您想要原始查询的结果,加上在 Table3(或 Table2)中找不到对应记录的 Table1 中的记录。这可以通过将您INNER JOIN的 s替换为LEFT JOINs 并将子句转换为WHILE子句来获得ON。然后你得到这个查询,即使在其他表中没有找到相应的记录,它也会从 Table1 中返回记录。

SELECT DISTINCT Table1.Table1Id, Table1.Field1, Table1.Field2,
               Table2.Field1, Table2.Field2,
               Table3.Field1, Table3.Field2
FROM (Table1 LEFT JOIN Table2
ON Table1.Table1Id = Table2.Table2Id)
LEFT JOIN Table3
ON Table1.Table1Id = Table3.Table3Id
AND Table3.AuditDate =
    (SELECT MAX(AuditDate) FROM Table3
     WHERE Table1.Table1Id = Table3.Table3Id)
于 2012-12-18T00:02:33.310 回答
0

这可能会帮助你,

select Table1Id,field1,field2 from Table1,Table2,Table3 
    where 
        Table1.Table1Id=Table2.Table2Id and 
        Table1.Table1Id=Table3.Table2Id and 
        Table2.AuditDate=Table3.AuditDate 
    group by Table1Id,field1,field2 
    having Table2.AuditDate = (
        Select max(AuditDate) from Table1,Table2,Table3 
            where  
                Table1.Table1Id=Table2.Table2Id and 
                Table1.Table1Id=Table3.Table2Id and  
                Table2.AuditDate=Table3.AuditDate 
            group by Table2.AuditDate
    );
于 2012-12-17T14:13:34.590 回答
-2

尝试

SELECT * FROM Table1 AS T1
    JOIN Table2 AS T2 ON T1.Table1Id = T2.Table1Id 
    JOIN Table3 AS T3 ON T1.Table1Id = T3.Table1Id 
    GROUP BY T2.AuditDate
于 2012-12-17T14:10:52.013 回答