SQL Server:并置和where子句

问题描述 投票:0回答:1

我正在尝试将两个表CustomerInvoice中的三列连接起来,创建一个新列,并找到其名称以SQl Server中的'Astridgruber'开头的new_id成员。

以下内容导致错误。

select 
    concat(c.FirstName, c.LastName, i.InvoiceId) as New_Id
from 
    Invoice i, Customer c
where 
    i.[CustomerId] = c.CustomerId 
where 
    New_Id = 'AstriGruber%'

非常感谢您的帮助。

这些是来自Chinook数据库的表:

image

sql sql-server
1个回答
2
投票

太久了,无法发表评论。您有几个问题:

  1. 您应该使用现代的,显式的JOIN语法,而不是逗号联接;
  2. WHERE子句过多; AND个条件一起;
  3. 您不能在WHERE子句中使用别名;将New_Id替换为concat(c.FirstName,c.LastName,i.InvoiceId);
  4. 您应该使用LIKE,而不是=

您的所有查询应如下所示:

select concat(c.FirstName,c.LastName,i.InvoiceId) as New_Id
from Invoice i
join Customer c on i.CustomerId = c.CustomerId 
where concat(c.FirstName,c.LastName,i.InvoiceId) LIKE 'AstriGruber%'

Demo on dbfiddle

© www.soinside.com 2019 - 2024. All rights reserved.