Goodmorning每个人,我在Access 2010中进行查询,我得到一个奇怪的行为,所以我想听听你的意见,我们走了:
SELECT X.*, L.CodLinea
FROM (
SELECT TOP 1 'LBASE' AS CodLinea, 'Linea Base' AS Descrizione FROM ParametriAzienda
) AS X LEFT JOIN Linee AS L
ON X.CodLinea = L.CodLinea
内部查询总是给出一行,其中有两个列应该类似于:
CodLinea | Descrizione
----------+--------------
LBASE | Linea Base
现在,像上面那样进行左连接应返回一行,其中一行名为L.CodLinea,其值为EQUAL为'LBASE'或NULL,具体取决于表Linee内部是否有“LBASE”。所以,结果可能是:
X.CodLinea | X.Descrizione | L.CodLinea
+-------------+-----------------+--------------+
LBASE | Linea Base | LBASE
如果值存在,或
X.CodLinea | X.Descrizione | L.CodLinea
+-------------+-----------------+--------------+
LBASE | Linea Base | null
如果该值不存在。的确,我得到的是:
X.CodLinea | X.Descrizione | L.CodLinea
+-------------+-----------------+--------------+
LBASE | Linea Base | 0
LBASE | Linea Base | 0
LBASE | Linea Base | 0
LBASE | Linea Base | 0
LBASE | Linea Base | 0
这绝对不可能,因为:a)我应该只得到一排; b)0与LBASE不相等或类似。如果我使用WHERE而不是LEFT JOIN(类似于INNER JOIN)或者RIGHT JOIN,结果是正确的(0行)。
可能是什么事?
编辑:实际上,ParametriAzienda只有一行而Linee不包含LBASE值。
答案 0 :(得分:1)
问题是TOP 1
:要么误解了它的使用(代码中的错误),要么就是引擎中的错误。
就个人而言,我总是使用DISTINCT
,因为它是标准SQL(我理解它的用途:)的确,当我测试它时,用TOP 1
替换DISTINCT
会将您的实际结果变为预期的结果。
这是我的复制品。下面的VBA在临时文件夹中创建一个新的数据文件,包含表格和示例数据。无需参考,只需复制+粘贴到任何VBA模块,例如使用Excel:
Sub NotTop1()
On Error Resume Next
Kill Environ$("temp") & "\DropMe.accdb"
On Error GoTo 0
Dim cat
Set cat = CreateObject("ADOX.Catalog")
With cat
.Create _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & _
Environ$("temp") & "\DropMe.accdb"
With .ActiveConnection
Dim Sql As String
Sql = _
"CREATE TABLE ParametriAzienda (x INTEGER NOT NULL);"
.Execute Sql
Sql = _
"INSERT INTO ParametriAzienda (x) VALUES (1);"
.Execute Sql
Sql = _
"CREATE TABLE Linee (CodLinea CHAR(1) NOT NULL);"
.Execute Sql
Dim i As Long
For i = 0 To 4
Sql = _
"INSERT INTO Linee (CodLinea) VALUES ('0');"
.Execute Sql
Next
Sql = _
"SELECT X.*, L.CodLinea " & _
"FROM ( " & _
" SELECT TOP 1 'LBASE' AS CodLinea, 'Linea Base' AS Descrizione FROM ParametriAzienda " & _
") AS X LEFT JOIN Linee AS L " & _
"ON X.CodLinea = L.CodLinea"
Dim rs
Set rs = .Execute(Sql)
MsgBox rs.GetString(2, , vbTab & vbTab, , "<null>")
Sql = Replace$(Sql, "TOP 1", "DISTINCT")
Set rs = .Execute(Sql)
MsgBox rs.GetString(2, , vbTab & vbTab, , "<null>")
End With
Set .ActiveConnection = Nothing
End With
End Sub