簡體   English   中英

在子查詢中引用主表

[英]Referencing the primary table in a sub-query

我有一些關系的表:

create table Students
(
    [id] uniqueidentifier not null,
    primary key (id),
    [group] uniqueidentifier FOREIGN KEY REFERENCES [Groups]([id]) not null,
    [name] nvarchar(20),
    [surname] nvarchar(20)
)

create table Books
(
    [id] uniqueidentifier not null,
    primary key (id),
    [name] nvarchar(100) not null,
    [pages] int not null,
    [author] uniqueidentifier FOREIGN KEY REFERENCES [Authors]([id])
)

create table StudentsCards
(
    [id] uniqueidentifier not null,
    primary key (id),
    [student] uniqueidentifier FOREIGN KEY REFERENCES [Students]([id])
)

create table RelationsBooksToStudentsCards
(
    [book] uniqueidentifier FOREIGN KEY REFERENCES [Books]([id]) not null,
    [students_card] uniqueidentifier FOREIGN KEY REFERENCES [StudentsCards]([id]) not null
)

我有查詢試圖獲取學生的總頁數:

SELECT 
    [id] AS student_id, [name], [surname], 
    (SELECT SUM(b.pages)
     FROM Students AS s
     INNER JOIN RelationsBooksToStudentsCards AS r ON (SELECT [id] FRM StudentsCards WHERE student = s.id) = r.students_card
     INNER JOIN Books AS b ON r.book = b.id
     WHERE s.id LIKE student_id) 
FROM
    Students

問題:我需要做什么才能在查詢中使用student_id 因為現在我有一個例外:

無效的列名“student_id”

啊,這很容易:

select [id], [name], [surname], (SELECT sum(b.pages)
FROM Students as s
inner JOIN RelationsBooksToStudentsCards as r
    ON (select [id] from StudentsCards where student = s.id) = r.students_card
inner JOIN Books as b
    ON r.book = b.id
where s.id like myAlias.id) from Students as myAlias

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM