Joint query questions for mysql, ask for help

the structure of the table is as follows: article table:

id  title   cid
1   xxx     5
2   xxx2    6
3   xxxx3   7

article_line relation table

article_id  line_id
1           20
1           21
1           22
2           20
2           28
2           40

now the demand is: query line_id is equal to 20, and the article cid=6, and exclude the data of line_id=21, for example, the above article_id=2 is consistent, equal to 1 is not consistent

ask the Great God for help

May.08,2021

select * from article where cid=6 and id in (select article_id from article_line where line_id=20)


Don't you find it contradictory that

query line_id equals 20, and the article cid=6, and excludes the requirement of line_id=21 ? Since Filter has only line_id=20, then the result set still needs to exclude line_id=21?.

is your real need to query all articles whose line_id is equal to 20 but not equal to 21?

this scenario uses the Exists statement

SELECT a.*
FROM article a
WHERE 
  EXISTS(SELECT al.article_id
             FROM article_line al
             WHERE al.line_id = 20 AND al.article_id = a.id)
  AND NOT EXISTS(
    SELECT al.article_id
    FROM article_line al
    WHERE al.line_id = 21 AND al.article_id = a.id)
  )
Menu