简体   繁体   English

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

[英]Select a value based on multiple rows in MySql

If I have the following example table: 如果我有以下示例表:


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

How can I select the docId where the tagId is both 2 and 3, ie docId = 13. 如何可以选择的docId其中TAGID既是2和3,即的docId = 13。

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

Assuming that (docId, tagId) combination is unique: 假设(docId, tagId)组合是唯一的:

SELECT  docId
FROM    mytable
WHERE   tagId IN (2, 3)
GROUP BY
        docId
HAVING  COUNT(*) = 2
SELECT docId
FROM my_table
WHERE tagId >= 2
AND tagId <= 3;

use Self Join . 使用自我加入

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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM