SQL:获取与每个其他所有其他值都必须在另一个表中的值

问题描述

我正在使用包含该数据库PHPMysqL网页:

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));

因此,我需要执行具有满足以下任何条件的动作的查询

  1. 它不在spawnConditions中。
  2. 如果它在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”。