我有以下代码(我正在使用Northwind数据库),这些代码为我显示了此picture
中显示的结果SELECT a.FirstName, a.TitleOfCourtesy, a.Notes, c.CustomerYear
FROM employees a
INNER JOIN orders b
ON a.EmployeeID = b.EmployeeID
LEFT JOIN customers c
ON b.CustomerID = c.CustomerID
WHERE a.TitleOfCourtesy = 'Ms.';
上面的代码结合了三个表,并仅选择a.TitleOfCourtesy = 'Ms.'
的行
从结果中,我想获取列%1992%
中具有a.Notes
的行,并且只显示c.CustomerYear
等于1992的行。因此在上图中,我应该只显示第二行。
我以为我可以使用CASE + WHEN语法来创建一种IF语句,但是我只会在CASE行中使用无效的语法。应该将CASE部件移到WHERE部件之后还是我完全错误地使用它?
SELECT a.FirstName, a.TitleOfCourtesy, a.Notes, c.CustomerYear
CASE
WHEN a.Notes LIKE '%1992%' THEN c.CustomerYear LIKE '1992'
ELSE NULL END
FROM employees a
INNER JOIN orders b
ON a.EmployeeID = b.EmployeeID
LEFT JOIN customers c
ON b.CustomerID = c.CustomerID
WHERE a.TitleOfCourtesy = 'Ms.';
我应该如何达到我想要的结果?
答案 0 :(得分:1)
您只需要扩展WHERE
子句...
SELECT a.FirstName, a.TitleOfCourtesy, a.Notes, c.CustomerYear
FROM employees a
INNER JOIN orders b
ON a.EmployeeID = b.EmployeeID
LEFT JOIN customers c
ON b.CustomerID = c.CustomerID
WHERE a.TitleOfCourtesy = 'Ms.'
AND a.Notes LIKE '%1992%'
AND c.CustomerYear LIKE '1992';
我还只会在图像中看到 一个 匹配行,而不是两个。所以我可能误会了您想要实现的目标...也许您希望它获得两行?
SELECT a.FirstName, a.TitleOfCourtesy, a.Notes, c.CustomerYear
FROM employees a
INNER JOIN orders b
ON a.EmployeeID = b.EmployeeID
LEFT JOIN customers c
ON b.CustomerID = c.CustomerID
WHERE a.TitleOfCourtesy = 'Ms.'
AND a.Notes LIKE '%1992%'
AND (c.CustomerYear LIKE '1992' OR c.CustomerYear IS NULL)
最后,您不需要LIKE '1992'
即可使用= '1992'
,如果值是整数,则只需使用= 1992
...