如何解决SQL:获取与每个其他所有其他值都必须在另一个表中的值
我正在使用包含该数据库的PHP和MySQL网页:
CREATE TABLE action (
idaction INT NOT NULL AUTO_INCREMENT,--Other columns
PRIMARY KEY (`idaction`));
CREATE event (
idevent INT NOT NULL AUTO_INCREMENT,--Other columns
PRIMARY KEY (`idevent`));
CREATE TABLE currentGame (
user_email VARCHAR(45) NOT NULL,--Other columns
PRIMARY KEY (`user_email`));
CREATE TABLE IF NOT EXISTS currentEvents (
currentGame_user_email VARCHAR(45) NOT NULL,event_idevent INT NOT NULL,PRIMARY KEY (currentGame_user_email,event_idevent),FOREIGN KEY (currentGame_user_email) REFERENCES currentGame (user_email),FOREIGN KEY (event_idevent) REFERENCES event (idevent));
CREATE TABLE IF NOT EXISTS spawnConditions (
action_idaction INT NOT NULL,PRIMARY KEY (action_idaction,FOREIGN KEY (action_idaction) REFERENCES action (idaction),FOREIGN KEY (event_idevent) REFERENCES event (idevent));
因此,我需要执行具有满足以下任何条件的动作的查询:
- 它不在
spawnConditions
中。 - 如果它在
spawnConditions
中,则该表中与之相关的所有事件都必须在currentEvent
的子组中,并且具有已知的user_email
。
换句话说,对于动作A1(位于事件{1}和事件E2中的spawnConditions
中),以便能够从表action
中进行选择,E1和E2都必须位于currentEvents
中与已知的currentGame_user_email
。
可以仅使用SQL编写它吗,还是需要使用PHP?
解决方法
我认为not exists
可以在这里完成工作。基本上,您想用currentEvents
来过滤currentGame_user_email
中存在对应记录的操作,而不是固定值:
select a.*
from action a
where not exists (
select 1
from spawnConditions sc
inner join currentEvents ce
on ce.event_idevent = sc.event_idevent
where
sc.action_idaction = a.idaction
and ce.currentGame_user_email <> ?
)
问号代表您在问题中提到的“某些已知的user_email”。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。