繁体   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