how to check child table all column values are negative in sql

I would use a sub-query get the FK ids of the entries that has positives values, and then use the result of that query to filter in the main query using a WHERE NOT IN clause

Schema (MySQL v5.7)

CREATE TABLE A (
  `id` INTEGER PRIMARY KEY
);

INSERT INTO A
  (`id`)
VALUES
  (1),
  (2),
  (3);

CREATE TABLE B (
  `id` INTEGER,
  `value` INTEGER,
  `fk_a` INTEGER,
  FOREIGN KEY (fk_a) REFERENCES A (id)
);

INSERT INTO B
  (`id`, `value`, `fk_a`)
VALUES
  (1, -5, 1),
  (2, -7, 1),
  (3, 5, 2),
  (4, -10, 3),
  (5, 20, 3);

Query #1

SELECT * FROM A
WHERE A.id NOT IN
(
  SELECT tb.fk_a
  FROM B tb
  WHERE tb.`value` >= 0
);

Output

| id  |
| --- |
| 1   |

View on DB Fiddle

Leave a Comment