我不是一个sql master,这句话对我来说没有意义。因此,如果任何人能够为我分解并让我知道究竟是什么,我会非常感激。
声明:
SELECT a.accountid,a.firstname,a.lastname,a.miName,a.legacyAccountid,a.accountType,
SELECT count(invoices.invID) AS InvCount
FROM invoices
WHERE invoices.accountid = a.accountid AND invoices.statusID=0 AND invoices.Remaining>0
AND dueDate < DATEADD(Day,1,GETDATE()) AS AccountStatus,
SELECT count(lotOwnership.lotNumb) AS LotCount FROM lotOwnership WHERE lotOwnership.accountid = a.accountid AS Active
FROM a
WHERE a.accountid LIKE % var % OR a.legAccountid LIKE % var % OR a.lastname LIKE % var % AND a.accountType=1 ORDER BY a.lastname, a.firstname
我很想知道的是:
图中的frack是如何合法的?我引用了整个语句,特别是这个嵌套的select:
SELECT count(lotOwnership.lotNumb) AS LotCount FROM lotOwnership WHERE lotOwnership.accountid = a.accountid AS Active
出于某种原因,我无法绕过这个。有人请救救我!我不明白一个选择语句如何有两个AS别名??????????????????????
答案 0 :(得分:2)
相关的子查询需要用括号括起来。然后,它是有道理的,因为它们产生标量值,然后用AS
别名。
如果OP中的代码运行,那么应用程序必须知道如何在没有添加括号的情况下隔离子查询。
SELECT
a.accountid,
a.firstname,
a.lastname,
a.miName,
a.legacyAccountid,
a.accountType,
(SELECT
count(invoices.invID) AS InvCount
FROM invoices
WHERE invoices.accountid = a.accountid
AND invoices.statusID=0
AND invoices.Remaining>0
AND dueDate < DATEADD(Day,1,GETDATE())) AS AccountStatus,
(SELECT
count(lotOwnership.lotNumb) AS LotCount
FROM lotOwnership
WHERE lotOwnership.accountid = a.accountid) AS Active
FROM a
WHERE a.accountid LIKE % var %
OR a.legAccountid LIKE % var %
OR a.lastname LIKE % var %
AND a.accountType=1
ORDER BY a.lastname, a.firstname
答案 1 :(得分:1)
代码缺少子查询周围的括号和字符串周围的引号:
SELECT a.accountid,a.firstname,a.lastname,a.miName,a.legacyAccountid,a.accountType,
(SELECT count(invoices.invID) AS InvCount
FROM invoices
WHERE invoices.accountid = a.accountid AND invoices.statusID=0 AND invoices.Remaining>0
AND dueDate < DATEADD(Day,1,GETDATE())
) AS AccountStatus,
(SELECT count(lotOwnership.lotNumb) AS LotCount FROM lotOwnership WHERE lotOwnership.accountid = a.accountid
) AS Active
FROM a
WHERE a.accountid LIKE' % var %' OR a.legAccountid LIKE '% var %' OR a.lastname LIKE '% var %' AND a.accountType=1
ORDER BY a.lastname, a.firstname
我对丑陋的编码风格进行了极少的重新格式化,因此您可以看到更改的位置。知道为什么这些字符丢失了吗?
编辑:
考虑select
的前两行(现在格式更好):
SELECT a.accountid, a.firstname, a.lastname, a.miName, a.legacyAccountid, a.accountType,
(SELECT count(invoices.invID) AS InvCount
FROM invoices
WHERE invoices.accountid = a.accountid AND
invoices.statusID = 0 AND
invoices.Remaining > 0 AND
dueDate < DATEADD(Day,1,GETDATE())
) AS AccountStatus,
子查询定义为返回名为InvCount
的列。如果您单独运行它,它将有一个名为InvCount
的列。
在此上下文中,它是一个标量子查询。也就是说,返回(最多)一行和一个值的子查询。在该上下文中,返回的值被视为表达式的结果。因此,子查询中名为InvCount
的列在外部查询中名为AccountStatus
。您可以将其视为:
select ((select . . . ) as InvCount) as AccountStatus
当然,这种语法不合法,但它从概念上捕捉了会发生什么。第一个别名被忽略了。