Всем Привет,
eсть 2 сщности m:n
CREATE TABLE anything (id INT AUTO_INCREMENT NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB
CREATE TABLE status (id INT AUTO_INCREMENT NOT NULL, datum DATE DEFAULT NULL, description VARCHAR(255) DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB
CREATE TABLE status_anything (status_id INT NOT NULL, anything_id INT NOT NULL, INDEX IDX_101374B26BF700BD (status_id), INDEX IDX_101374B2A5C80A8D (anything_id), PRIMARY KEY(status_id, anything_id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB
ALTER TABLE status_anything ADD CONSTRAINT FK_101374B26BF700BD FOREIGN KEY (status_id) REFERENCES status (id) ON DELETE CASCADE
ALTER TABLE status_anything ADD CONSTRAINT FK_101374B2A5C80A8D FOREIGN KEY (anything_id) REFERENCES anything (id) ON DELETE CASCADE
Этот код как бы делает то что я хочу, но возможно ли всё это зделать одним запросом, без subselect?
SELECT distinct iw.id
from anything iw
LEFT JOIN status_anything si on iw.id = si.anything_id
LEFT JOIN status s on s.id = si.status_id
WHERE s.datum between '2023-03-01' and '2023-05-01'
and iw.id not in (SELECT distinct iw.id
from anything iw
LEFT JOIN status_anything si on iw.id = si.anything_id
LEFT JOIN status s on s.id = si.status_id
WHERE s.datum between '2022-03-01' and '2023-03-01')