在Access中加入两个查询

时间:2015-04-02 20:09:02

标签: sql-server ms-access

我有四张桌子:

客户

ID | CLIENT_NUM | Year

农场

ID | ClientID | FARM_NUM

字段

ID | FarmID | FIELD_NUM | RANK

SoilSheet

ID | FarmID | FieldID | SAMP_NUM | Year

我需要从Rank,FIELD_NUM和Year订购的Soilsheet中获取数据。所以,我试过这个:

SELECT FL.Rank,FL.FIELD_NUM, S.Year, SAMP_NUM 
FROM (((SoilSheet S 
INNER JOIN Farms F ON F.ID = S.FarmID)
INNER JOIN Clients C ON C.ID = F.ClientID) 
INNER JOIN Fields FL ON FL.ID = S.FieldID)
WHERE C.CLIENT_NUM = 1 AND F.FARM_NUM = 1
ORDER BY C.CLIENT_NUM, F.FARM_NUM, FL.Rank, FL.FIELD_NUM, S.Year

问题是RANK每年都会有所不同,所以它没有正确排序。例如,我需要按当年的RANK顺序订购。

通过上述内容,我得到的结果如下:

RANK | FIELD_NUM | Year | SAMP_NUM
   0 |      19-2 | 2015 | 3000
   2 |      20-1 | 2015 | 3001
   2 |      20-1 | 2014 | 2002
   2 |      20-1 | 2015 | 1003
  20 |      19-2 | 2014 | 2001

19-2在2015年排名0,但在2014年排名20.所以,我尝试了这个:

SELECT FL.Rank,FL.FIELD_NUM, S.Year, SAMP_NUM
FROM ((Clients C 
INNER JOIN Farms F ON F.ClientID = C.ID) 
INNER JOIN Fields FL ON FL.FarmID = F.ID)
LEFT JOIN (((SoilSheet S
INNER JOIN Fields FLS ON FLS.ID = S.FieldID)
INNER JOIN Farms FS ON FS.ID = S.FarmID)
INNER JOIN Clients CS ON CS.ID = FS.ClientID) 
ON 
(FLS.FIELD_NUM = FL.FIELD_NUM 
AND FS.FARM_NUM = F.FARM_NUM 
AND CS.CLIENT_NUM = C.CLIENT_NUM)
WHERE C.CLIENT_NUM = 1 AND F.FARM_NUM = 1 AND C.Year = 2015  
ORDER BY C.CLIENT_NUM, F.FARM_NUM, FL.Rank, FL.FIELD_NUM, S.Year

这在SQL Server中运行良好:

RANK | FIELD_NUM | Year | SAMP_NUM
   0 |      19-2 | 2015 | 3000
   0 |      19-2 | 2014 | 2001
   2 |      20-1 | 2015 | 3001
   2 |      20-1 | 2014 | 2002
   2 |      20-1 | 2015 | 1003

在Access中,它不支持“加入”表达式。'。我猜它是因为Access并不喜欢加入INNER联接,但我只是在猜测。

任何想法?订购或其他方式加入的另一种方式?

2 个答案:

答案 0 :(得分:1)

我终于开始工作了

SELECT C1.Year,C1.RANK, C1.FIELD_NUM, C.CLIENT_NUM, F.FARM_NUM FROM
(SELECT C.Year,FL.RANK, FL.FIELD_NUM, C.CLIENT_NUM, F.FARM_NUM FROM 
((Clients C 
INNER JOIN Farms F ON F.ClientID = C.ID) 
INNER JOIN Fields FL ON FL.FarmID = F.ID)) C1
LEFT JOIN 
(SELECT S.Year, SAMP_NUM,FLS.FIELD_NUM, FS.FARM_NUM, CS.CLIENT_NUM 
FROM ((SoilSheet S
INNER JOIN Fields FLS ON FLS.ID = S.FieldID)
INNER JOIN Farms FS ON FS.ID = S.FarmID)
INNER JOIN Clients CS ON CS.ID = FS.ClientID) S1
ON (S1.FIELD_NUM = C1.FIELD_NUM AND S1.FARM_NUM = C1.FARM_NUM 
AND S1.CLIENT_NUM = C1.CLIENT_NUM)
WHERE C.CLIENT_NUM = 1 AND F.FARM_NUM = 1 AND C.Year = 2015  
ORDER BY FL.Rank, FL.FIELD_NUM 

答案 1 :(得分:0)

您是否尝试将TSQL从SQL Server复制到Access?不幸的是,在没有修改连接的情况下,它不会工作。具体来说,您需要在join子句中添加括号。

查看此信息以获取更多信息:

SQL Inner Joins with multiple tables