简体   繁体   English

多对多关系,根据一侧的元素查询一侧

[英]many-to-many relationship,, querying one side depending on its elements

Here is the most relevant part of my database schema: 这是我的数据库架构中最相关的部分:

create table TEST (
    ID integer not null,
    NAME text not null,
    constraint PK_TEST primary key (ID),
    constraint UNQ_TEST_NAME unique (NAME)
);

create table SESSION (
    ID integer not null,
    constraint PK_SESSION primary key (ID)
);

create table SESSION_TEST (
    SESSION_ID integer not null,
    TEST_ID integer not null,
    ORDINAL integer not null,
    constraint PK_SESSION_TEST primary key (SESSION_ID, TEST_ID),
    constraint FK_SESSION_TEST_SESSION_ID foreign key (SESSION_ID) references SESSION (ID) on delete cascade,
    constraint FK_SESSION_TEST_TEST_ID foreign key (TEST_ID) references TEST (ID) on delete cascade,
    constraint UNQ_SESSION_TEST_SESSION_ID_ORDINAL unique (SESSION_ID, ORDINAL)
);

There are SESSIONS that consist of multiple TESTS. 有些会话包含多个TESTS。 TESTs in SESSIONS have ORDINALs (are ordered). SESSIONS中的TEST具有ORDINAL(已订购)。 SESSION_TEST is a link table for a many-to-many relationship: one test can be a part of multiple sessions, and one session consists of multiple tests (but one test can be in a session only once, which is the PK). SESSION_TEST是用于多对多关系的链接表:一个测试可以是多个会话的一部分,一个会话可以包含多个测试(但是一个测试只能在一个会话中出现一次,即PK)。

I am having problems writing an SQL statement that would return true (or 1 actually, as I am using SQLite) for a test with a given ID, if there is a session that has that test and only that test (in other words, the session consists of only one test, the one I am looking for). 如果存在具有该测试且仅该测试的会话(换句话说,会话仅包含一项测试,我正在寻找一种测试)。 For example: 例如:

TEST:
ID|NAME
1|aaa
2|bbb
3|ccc

SESSION:
ID
1
2
3
4

SESSION_TEST:
SESSION_ID|TEST_ID|ORDINAL
1|1|1
1|2|2
2|1|1
3|3|1

SESSION with ID = 1 has two TESTs, and SESSIONs 2 and 3 have one test each. ID = 1的SESSION具有两个TEST,SESSION 2和3分别具有一个测试。 I would need to have a select that would return 1/true for inputs 1 and 3, but 0 for 2 (as this TEST is only in SESSION 1, but it's not the only one). 我需要一个选择,对于输入1和输入3将返回1 / true,但对于输入2将返回0(因为此TEST仅在SESSION 1中,但不是唯一的)。

(Sorry about the title, I really didn't know how to put it in a few sentences and make it clear!). (对不起标题,我真的不知道如何用几句话把它弄清楚!)。

RETURN EXISTS SELECT SESSION_ID FROM 
SESSION_TEST
WHERE TEST_ID = @id
AND ORDINAL = 1
AND SESSION_ID NOT IN (SELECT SESSION_ID FROM SESSION_TEST WHERE ORDINAL > 1);

The RETURN EXISTS syntax might be TSQL only, but you get the picture. RETURN EXISTS语法可能仅是TSQL,但是您可以理解。 If the query returns rows, return true, if not return false. 如果查询返回行,则返回true,否则返回false。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM