SQL嵌套查询不返回任何内容

时间:2016-02-25 02:08:34

标签: mysql sql

我是SQL的初学者,很难理解逻辑查询。在这个特殊问题中,我试图找到在加利福尼亚购买的Track。

以下是表格。

CREATE TABLE [InvoiceLine]
(
[InvoiceLineId] INTEGER  NOT NULL,
[InvoiceId] INTEGER  NOT NULL,
[TrackId] INTEGER  NOT NULL,
[UnitPrice] NUMERIC(10,2)  NOT NULL,
[Quantity] INTEGER  NOT NULL,
CONSTRAINT [PK_InvoiceLine] PRIMARY KEY  ([InvoiceLineId]),
FOREIGN KEY ([InvoiceId]) REFERENCES [Invoice] ([InvoiceId]) 
    ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([TrackId]) REFERENCES [Track] ([TrackId]) 
    ON DELETE NO ACTION ON UPDATE NO ACTION
);

CREATE TABLE [Invoice]
(
[InvoiceId] INTEGER  NOT NULL,
[CustomerId] INTEGER  NOT NULL,
[InvoiceDate] DATETIME  NOT NULL,
[BillingAddress] NVARCHAR(70),
[BillingCity] NVARCHAR(40),
[BillingState] NVARCHAR(40),
[BillingCountry] NVARCHAR(40),
[BillingPostalCode] NVARCHAR(10),
[Total] NUMERIC(10,2)  NOT NULL,
CONSTRAINT [PK_Invoice] PRIMARY KEY  ([InvoiceId]),
FOREIGN KEY ([CustomerId]) REFERENCES [Customer] ([CustomerId]) 
    ON DELETE NO ACTION ON UPDATE NO ACTION
);

CREATE TABLE [Track]
(
[TrackId] INTEGER  NOT NULL,
[Name] NVARCHAR(200)  NOT NULL,
[AlbumId] INTEGER,
[MediaTypeId] INTEGER  NOT NULL,
[GenreId] INTEGER,
[Composer] NVARCHAR(220),
[Milliseconds] INTEGER  NOT NULL,
[Bytes] INTEGER,
[UnitPrice] NUMERIC(10,2)  NOT NULL,
CONSTRAINT [PK_Track] PRIMARY KEY  ([TrackId]),
FOREIGN KEY ([AlbumId]) REFERENCES [Album] ([AlbumId]) 
    ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([GenreId]) REFERENCES [Genre] ([GenreId]) 
    ON DELETE NO ACTION ON UPDATE NO ACTION,
FOREIGN KEY ([MediaTypeId]) REFERENCES [MediaType] ([MediaTypeId]) 
    ON DELETE NO ACTION ON UPDATE NO ACTION
);

这是我尝试过的。

SELECT T.name
FROM Track T, InvoiceLine L
WHERE T.trackid=L.trackid AND
L.invoiceid IN (SELECT I.invoiceid
FROM Invoice I
WHERE I.billingcity="California");

查询不返回任何内容。逻辑有什么问题?

1 个答案:

答案 0 :(得分:0)

SELECT
      T.name
FROM Track T
      INNER JOIN InvoiceLine L ON T.trackid = L.trackid
      INNER JOIN invoice I ON L.InvoiceId = I.InvoiceId
WHERE I.BillingState = 'California'

Track加入加入InvoiceLine

Invoice

请不要使用古老的加入where子句的方式。对此最简单的技巧是禁止表之间的任何逗号,例如请注意逗号:FROM Track T, InvoiceLine L - 请避免使用。

我假设你希望加利福尼亚州在BillingState举行,而不是那个名字的城市(如果有的话)。