这有点复杂,但我尽可能简化它。我有一个包含名字姓氏等的联系人表。它还包含2列,表示联系人所关联的组(src)以及该组中的id(uID)。我正在尝试进行联系人搜索。所以,如果我正在寻找迈克,这很简单
... WHERE fname LIKE '%mik%'.
返回所有麦克风。我现在要做的是根据群组或名称进行搜索。所以,如果我想要所有与groupA相关的联系人;我会去
.. WHERE fname LIKE '%mik%' OR code LIKE '%groupA%'.
不幸的是,这会返回错误
'无效的列名代码'。
这是我的实际SQL的样子:
SELECT
c.contactID,
CASE c.src
WHEN 0 THEN (SELECT tbl.code FROM CSA.dbo.Clients tbl WHERE clientID=c.uID)
WHEN 1 THEN (SELECT tbl.scac FROM CSA.dbo.Carriers tbl WHERE carrierID=c.uID)
WHEN 2 THEN (SELECT tbl.code FROM codeBase tbl WHERE cID=c.uID)
END as code,
fName+' '+lname,
cType
FROM contacts c
WHERE fname LIKE '%mi%' OR code LIKE '%mi%'
因此,您可以看到我根据他们拥有的组和ID返回代码。如何搜索该代码列?
答案 0 :(得分:2)
尝试:
SELECT
c.contactID,
CASE c.src
WHEN 0 THEN (SELECT tbl.code FROM CSA.dbo.Clients tbl WHERE clientID=c.uID)
WHEN 1 THEN (SELECT tbl.scac FROM CSA.dbo.Carriers tbl WHERE carrierID=c.uID)
WHEN 2 THEN (SELECT tbl.code FROM codeBase tbl WHERE cID=c.uID)
END as code,
fName+' '+lname,
cType
FROM contacts c
WHERE fname LIKE '%mi%' OR
CASE c.src
WHEN 0 THEN (SELECT tbl.code FROM CSA.dbo.Clients tbl WHERE clientID=c.uID)
WHEN 1 THEN (SELECT tbl.scac FROM CSA.dbo.Carriers tbl WHERE carrierID=c.uID)
WHEN 2 THEN (SELECT tbl.code FROM codeBase tbl WHERE cID=c.uID)
END LIKE '%mi%'
或者使用CTE:
;WITH CTE
AS
(
SELECT
c.contactID,
CASE c.src
WHEN 0 THEN (SELECT tbl.code FROM CSA.dbo.Clients tbl WHERE clientID=c.uID)
WHEN 1 THEN (SELECT tbl.scac FROM CSA.dbo.Carriers tbl WHERE carrierID=c.uID)
WHEN 2 THEN (SELECT tbl.code FROM codeBase tbl WHERE cID=c.uID)
END as code,
fName+' '+lname as fullname,
fname,
cType
FROM contacts c
)
SELECT *
FROM CTE
WHERE fname like '%mi%' or code like '%mi%'
答案 1 :(得分:1)
您可以使用common table expression获取结果,包括code
列,然后对其进行过滤。
WITH CTE AS (
SELECT
c.contactID,
CASE c.src
WHEN 0 THEN (SELECT tbl.code FROM CSA.dbo.Clients tbl WHERE clientID=c.uID)
WHEN 1 THEN (SELECT tbl.scac FROM CSA.dbo.Carriers tbl WHERE carrierID=c.uID)
WHEN 2 THEN (SELECT tbl.code FROM codeBase tbl WHERE cID=c.uID)
END as code,
fName+' '+lname AS fullname,
fName,
cType
FROM contacts c
)
SELECT contactID, code, fullname, cType FROM CTE
WHERE fname LIKE '%mi%' OR code LIKE '%mi%'
答案 2 :(得分:1)
至少有三种方法:
CASE
内的WHERE
- 建议不要这样做,因为您在SELECT
和WHERE
<之间重复了很多代码/ LI>
SELECT *
,并在外部WHERE
中使用其列 - 此方法相当便携