根据MySql中的多行选择一个值

时间:2011-03-14 16:11:08

标签: mysql select

如果我有以下示例表:


id   docId   tagId
1     12      2
2     13      2
3     13      3
4     13      4
5     14      3

如何选择 docId tagId 为2和3,即docId = 13。

4 个答案:

答案 0 :(得分:3)

select docId
    from YourTable
    where tagId in (2,3)
    group by DocId
    having count(distinct tagId) = 2

答案 1 :(得分:1)

假设(docId, tagId)组合是唯一的:

SELECT  docId
FROM    mytable
WHERE   tagId IN (2, 3)
GROUP BY
        docId
HAVING  COUNT(*) = 2

答案 2 :(得分:0)

SELECT docId
FROM my_table
WHERE tagId >= 2
AND tagId <= 3;

答案 3 :(得分:0)

使用自我加入

SELECT DISTINCT t1.docId 
    FROM test AS t1 
    INNER JOIN test AS t2
    ON (t1.docId = t2.docId and t1.tagId =2 AND t2.tagId =3)