简体   繁体   English

如何使用 SQL 从指定格式的多对多关系中提取数据以用于复选框?

[英]How do I extract data from a many to many relationship in a specified format for use in a checkbox using SQL?

ll The table structure is as shown below. ll 表结构如下图。 表结构

As an example, I want the enrollment details of a student, let's say the student with ID 3.例如,我想要一个学生的注册详细信息,假设 ID 为 3 的学生。

I expect the query result to be in the above format.我希望查询结果采用上述格式。 预期产出

I intend to use the true / false or 0, 1 column to be linked to a list of check-boxes at the front-end.我打算使用 true / false 或 0, 1 列链接到前端的复选框列表。 This way a student can check / uncheck his own enrolled courses easily.这样,学生可以轻松地选中/取消选中自己注册的课程。

More Info更多信息

My project will be created in ASP.Net MVC.我的项目将在 ASP.Net MVC 中创建。 So, I am OK with LINQ queries as well.所以,我也可以使用 LINQ 查询。 Assume standard model code with no annotations.假设没有注释的标准 model 代码。

EDIT: I didn't write my attempt as I simply didn't get far enough to post it here.编辑:我没有写我的尝试,因为我根本没有足够远来在这里发布它。 But here it is但在这里

SELECT COURSE.CNAME, 0
FROM COURSE
union
SELECT COURSE.CNAME, ENROLLMENT.EID
FROM COURSE INNER JOIN ENROLLMENT
ON COURSE.CID = ENROLLMENT.CID
INNER JOIN STUDENTS
ON STUDENTS.SID = ENROLLMENT.SID
WHERE STUDENTS.SID = 3

I think you want a left join .我想你想要一个left join This would give you the result you want for student 3 :这将为您提供学生3所需的结果:

select
    e.eid,
    c.cname,
    c.cid,
    case when e.eid is null then 0 else 1 end as isenrolled
from course c
left join enrollment e on e.cid = c.cid and e.sid = 3
order by is_enrolled desc, e.eid, c.cid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 SQL 使用 AND 搜索多对多关系 - How do I use SQL to search a many to many relationship using AND 如何在SQL中执行多对多关系聚合? - How do I perform a Many-to-Many relationship aggregation in SQL? 如何通过DBIx为多对多关系插入数据? - How do I insert data via DBIx for Many to Many relationship? 如何编写SQL查询以检查一个表上的多对多关系是否是另一个表上多对多关系的子集? - How do I write a SQL query to check if a many-to-many relationship on one table is a subset of a many-to-many relationship on another table? SQL 我怎么总结一个has many relationship - SQL how do I sum up a has many relationship 2多对多关系-通过联接提取数据 - 2 Many to Many relationship - extract data with join 如何使用sql获取oracle中一对多关系的数据? - How to get the data of one to many relationship in oracle using sql? sql多对多关系我在哪里把类型字段 - sql many to many relationship where do I put type field 在SQL中,我如何编写查询以从1对多关系返回1条记录? - In SQL how do I write a query to return 1 record from a 1 to many relationship? 如何在SQL中基于多对多关系的复选框搜索和过滤数据? - How to do Searching and Filtering Data based on Checkboxes in Many to Many Relationship in SQL?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM