对于家庭作业,我目前正试图弄清楚如何在使用JOIN时更新列,但我似乎无法做到正确。
第一部分是:
你工作的'公司'决定聘请一个新的双语支持职位。您的工作是找到购买了西班牙语轨道的所有用户,以便将他们分配给新的支持代表。销售已经开始识别所有被归类为西班牙语的专辑,到目前为止他们已经找到了AlbumId的8,21,22,23,24,25,26,27,28,29,32,33,34,41, 42,45,47,52,53。
我用这个查询解决了这个问题:
SELECT * FROM customers
JOIN invoices USING (CustomerId)
JOIN invoice_items USING (InvoiceId)
JOIN tracks USING (TrackId)
WHERE tracks.AlbumId IN (8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32, 33, 34, 41, 42, 45, 47, 52, 53)
GROUP BY invoices.InvoiceId;
现在第二部分是:
通过修改第1部分中的查询来帮助销售团队。不仅仅列出所有客户,还应该更新客户指定的支持代表。新支持代表的身份证是6。
我试过这个:
UPDATE customers
SET SupportRepId = 6
WHERE(SELECT * FROM customers
JOIN invoices USING (CustomerId)
JOIN invoice_items USING (InvoiceId)
JOIN tracks USING (TrackId)
WHERE tracks.AlbumId IN (8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32, 33, 34, 41, 42, 45, 47, 52, 53)
GROUP BY invoices.InvoiceId);
但我收到的错误是:
SQLITE_ERROR:子选择返回33列 - 预期为1 错误:1 代码:SQLITE_ERROR 名称:错误
答案 0 :(得分:0)
最后一个错误是线索。 WHERE检查1个值; 0为假,正为真。 *返回33个值(列)。
要满足多个更新需要使用相关子查询,例如WHERE IN或WHERE EXISTS将为更新处理的每一行提供结果。
使用 WHERE EXISTS
查询可以是: -
UPDATE customers
SET SupportRepId = 6
WHERE EXISTS (
SELECT 1 FROM customers AS B
JOIN invoices USING (CustomerId)
JOIN invoice_items USING (InvoiceId)
JOIN tracks USING (TrackId)
WHERE tracks.AlbumId IN (8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32, 33, 34, 41, 42, 45, 47, 52, 53)
AND B.CustomerId = customers.CustomerId
);
因此,如果客户的任何发票具有来自其中一个列出的相册的跟踪,并且来自相关子查询(B.CustomerId)的customerId与CustomerId相同,则将返回UPDATE 1处理的每一行。正在更新的行。
使用 WHERE IN
查询可以是: -
UPDATE customers
SET SupportRepId = 6
WHERE CustomerId IN (
SELECT CustomerId FROM customers
JOIN invoices USING (CustomerId)
JOIN invoice_items USING (InvoiceId)
JOIN tracks USING (TrackId)
WHERE tracks.AlbumId IN (8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32, 33, 34, 41, 42, 45, 47, 52, 53)
);
答案 1 :(得分:0)
我使用以下命令完成了这项工作:
UPDATE customers
SET SupportRepId = 6
WHERE CustomerId IN (
SELECT customers.CustomerId FROM customers
JOIN invoices USING (CustomerId)
JOIN invoice_items USING (InvoiceId)
JOIN tracks USING (TrackId)
WHERE AlbumId IN (8, 21, 22, 23, 24, 25, 26, 27, 28, 29, 32, 33, 34, 41, 42, 45, 47, 52, 53)
);