A
A
Alexander2020-11-27 18:46:23
MySQL
Alexander, 2020-11-27 18:46:23

SQL how to get data from the first table with the condition of having data in the second by a certain value?

Friends, I have already broken my head, tell me, please, how to build a query with the following conditions.
There are two tables, let's say article and photo.
Each article in the article table can have 0 to 5 photos of one type and 0 to 5 photos of another type. Let's say 'before' and 'after'. The column in the 'photo' table is named 'made'.
One row in the 'photo' table is one photo with either 'before' or 'after' in the corresponding field.

The request for getting articles for which there are no photos at all is like this:

SELECT title AS 'Заголовок статьи', article.id AS 'Id статьи' FROM article
LEFT JOIN `photo` ON photo.article_id = article.id
WHERE article_id IS NULL
GROUP BY article.id


I can't figure out how to make a query in such a way as to display only those articles that do not have a "Before" photo or an "After" photo added.
As far as I understand, you need to somehow make a selection based on the condition of the absence of records with a certain value of the "made" field.
Help me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Slava Rozhnev, 2020-11-27
@Klapanasos

It's pretty trivial:

SELECT `title` AS 'Заголовок статьи', `article`.`id` AS 'Id статьи' 
FROM `article`
LEFT JOIN `photo` ON `photo`.`article_id` = `article`.`id` AND `photo`.`made` = 'before' -- or 'after'
WHERE `article_id` IS NULL
GROUP BY `article`.`id`

Another variant:
SELECT `title` AS 'Заголовок статьи', `article`.`id` AS 'Id статьи' 
FROM `article`
WHERE NOT EXISTS (
    SELECT `article_id` 
    FROM `photo` 
    WHERE `photo`.`article_id` = `article`.`id` AND `photo`.`made` = 'before' -- or 'after'
);

execute SQL query on SQLize.online

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question