【问题标题】:How do I make this Access sql statement work with Sql Server?如何使此 Access sql 语句与 Sql Server 一起使用?
【发布时间】:2012-11-29 00:32:19
【问题描述】:

我几乎已经用 Sql Server 替换了我们的应用程序后端,但遇到了一个问题。以下 Access 查询不适用于 Sql Server。

SELECT table1.*
FROM   table1
       INNER JOIN (table2
                   INNER JOIN table3
                           ON ( table2.custkey = table3.custkey )
                              AND ( table2.sequence = table3.sequence ))
               ON table1.account = table2.account
WHERE  (( LEFT(table2.keyid, 1) = 'B' ))
ORDER  BY table3.lastname & table3.firstname,
          table1.account; 

我尝试了此语句的多种变体,但未能使其发挥作用。此声明的一些帮助将帮助我修改其他一些。任何帮助将不胜感激。

【问题讨论】:

  • 另一条评论。在您的 ORDER BY 中,您正在对派生字段(即姓氏 + 名字)进行排序。这将使 db 引擎首先组合 2 个字段,并对非索引结果进行排序。您可以改为 ORDER BY table3.lastname, table3.firstname, table1.account 这将为您提供相同的结果,但速度更快。

标签: sql-server ms-access join


【解决方案1】:

唯一突出的是“&”,即 SQL Server 中的+。但是访问中的&也将NULL值视为空字符串,需要在SQL Server中使用ISNULL进一步处理:

SELECT table1.*
FROM   table1
       INNER JOIN (table2
                   INNER JOIN table3
                           ON ( table2.custkey = table3.custkey )
                              AND ( table2.sequence = table3.sequence ))
               ON table1.account = table2.account
WHERE  (( LEFT(table2.keyid, 1) = 'B' ))
ORDER  BY isnull(table3.lastname,'') + isnull(table3.firstname,''),
          table1.account; 

如果我要从头开始在 SQL Server 中编写查询,我可能会连续执行连接,而不是在连接回 t1 之前在括号中执行 t2-t3。第一个字符的测试也将表示为 LIKE(个人偏好)。

  SELECT table1.*
    FROM table1
    JOIN table2 ON table1.account = table2.account
    JOIN table3 ON table2.custkey = table3.custkey AND table2.sequence = table3.sequence
   WHERE table2.keyid LIKE 'B%'
ORDER BY isnull(table3.lastname,'') + isnull(table3.firstname,''), table1.account;

【讨论】:

  • 感谢您的回复,我进行了这些更改,现在效果很好。它是“&”,我不得不把它改成 + 好几次,我的注意力集中了几圈。再次感谢。
【解决方案2】:
SELECT table1.*
FROM   table1
INNER JOIN table2  ON table1.account = table2.account
INNER JOIN table3  ON ( table2.custkey = table3.custkey ) 
                      AND ( table2.sequence = table3.sequence )
WHERE  LEFT(table2.keyid, 1) = 'B' 
ORDER  BY table3.lastname, table3.firstname, table1.account; 

如果希望 where 子句适用于索引,请使用 LIKE 重写:

SELECT table1.*
FROM   table1
INNER JOIN table2  ON table1.account = table2.account
INNER JOIN table3  ON ( table2.custkey = table3.custkey ) 
                      AND ( table2.sequence = table3.sequence )
WHERE  table2.keyid LIKE 'B%' 
ORDER  BY table3.lastname, table3.firstname, table1.account; 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多