没有连接的MySQL语句

没有连接的MySQL语句,mysql,join,where,Mysql,Join,Where,我有一个MySQL表,我试图查询文章和数据,我不想做任何连接到其他表 它具有以下行: article_id doc_type doc_type_id 1 1 2 1 2 1 2 1 2 3 1 2 3 2 1 我正在尝试编写一个查询,其中返回的doc\u type为1,doc\u type\u id为2,并且在同

我有一个MySQL表,我试图查询文章和数据,我不想做任何连接到其他表

它具有以下行:

article_id  doc_type  doc_type_id
1           1         2
1           2         1
2           1         2
3           1         2
3           2         1
我正在尝试编写一个查询,其中返回的
doc\u type
为1,
doc\u type\u id
为2,并且在同一
article\u id
中有另一行,其中
doc\u type
为2,
doc\u type\u id
为1,因此在上面的示例中,我尝试返回
article\u id
1和3


您知道如何编写SQL查询来实现这一点吗?

您不必连接到其他表,但可以通过自连接来实现

select distinct article_id
from articles_data ad
where 
    doc_type = 1 and 
    doc_type_id = 2 and
    article_id in (
        select article_id 
        from articles_data
        where 
            article_id = ad.article_id and 
            doc_type = 2 and 
            doc_type_id = 1
    )
这是我的想法,你可能需要调整语法

select distinct article_id
from articles_data a
join articles_data b on b.articles_id = a.articles_id
where a.doc_type = 1 and a.doc_type_id = 2
and b.doc_type = 2 and b.doc_type_id = 1

您可能可以使用子查询,但最简单的方法是使用联接。您想避免加入的任何特殊原因?这将返回所有三个article\u id值,不是吗?@karolis:The
article\u id=ad.article\u id和
应该被删除。@ypercube这是不需要的,但有了它,查询会更快。无论如何,我认为这是一个家庭作业,所以任何决定都是好的。
SELECT article_id
FROM article_data
WHERE (doc_type = 1 AND doc_type_id = 2)
   OR (doc_type = 2 AND doc_type_id = 1)
GROUP BY article_id
HAVING COUNT(DISTINCT doc_type) = 2 AND COUNT (DISTINCT doc_type_id) = 2
SELECT DISTINCT article_id
FROM article_data ad
WHERE doc_type = 1
  AND doc_type_id = 2
  AND EXISTS
    ( SELECT *
      FROM article_data ad2
      WHERE ad2.doc_type = 2
        AND ad2.doc_type_id = 1
        AND ad2.article_id = ad.article_id
    )