admin

sql查询以选择两列中具有相同id但不同值的记录

sql

现在查看一下articleid = 54的最后两个记录

我只想像一次选择该记录-我想为(fieldsid = 1和value = 1)和(fieldsid = 2和value =
1)选择具有相同articleid的所有记录

articleid必须相同,但它会为您在两个不同的记录所需的值。

请有人帮我。

我正在尝试这样做-

select n1.id, n1.fieldsid, n1.value 
from `tablename` n1 
where (n1.fieldsid='1' and n1.value='1') 
and n1.id = (select n2.id 
             from `tablename` n2 
             where (n1.fieldsid='2' and n2.value='2') 
             and n1.id=n2.id)

阅读 331

收藏
2021-07-01

共1个答案

admin

SELECT youtable.
FROM yourtable
WHERE articleid IN (SELECT articleid
FROM yourtable
WHERE (fieldsid, value) IN ((1,1),(2,1))
GROUP BY articleid
HAVING COUNT(
)=2)

编辑:如果只需要第一条记录:

SELECT youtable.*
FROM yourtable
WHERE id IN (SELECT MIN(id)
             FROM yourtable
             WHERE (fieldsid, value) IN ((1,1),(2,1))
             GROUP BY articleid
             HAVING COUNT(*)=2)
2021-07-01