MYSQL - 从多行,相同用户,不同值中选择

时间:2013-07-23 07:23:07

标签: mysql

下面是我的名为fittest的表格。我需要找到哪些学生根据学生ID(studid)进行了前置栏中指定的前后测试。因此,基于下面的简单表格,我需要返回studid 123456.如何为此编写SELECT查询?

SQL query: SELECT studid, prepost FROM `fittest` LIMIT 0, 30 ; 

    studid  prepost
    123456  pre
    123456  post
    1031460 pre

9 个答案:

答案 0 :(得分:4)

JOIN怎么样:

select s1.studid, s1.prepost, s2.prepost
from fittest s1
inner join fittest s2
    on s1.studid = s2.studid
where s1.prepost = 'pre' 
  and s2.prepost = 'post'

答案 1 :(得分:3)

尝试

SELECT studid
  FROM fittest
 GROUP BY studid
HAVING COUNT(DISTINCT prepost) = 2

或者如果您想确保只有一行pre,一行post,那么您可以像这样强制执行

SELECT studid
  FROM fittest
 GROUP BY studid
HAVING (MAX(prepost = 'pre' ) + 
        MAX(prepost = 'post')) = 2
   AND COUNT(DISTINCT prepost) = 2

输出:

| STUDID |
----------
| 123456 |

以下是两个查询的 SQLFiddle 演示

答案 2 :(得分:0)

尝试:

    select f1.studid
       from fittest f1
       inner join fittest f2
         on f1.studid = f2.studid
    where f1.prepost = 'pre' and f2.prepost = 'post'

这是SQL Fiddle

答案 3 :(得分:0)

根据您的真实主键,您可以使用以下内容:

SELECT studid
FROM fittest
WHERE prepost = 'pre' OR prepost = 'post'
GROUP BY studid
HAVING COUNT(DISTINCT prepost) = 2

答案 4 :(得分:0)

SELECT t1.studid
FROM fittest t1
INNER JOIN t2 ON t1.studid=t2.studid
WHERE t1.prepost = 'pre'
AND t2.prepost='post'

答案 5 :(得分:0)

如果此列中只能进行PRE和POST,请尝试

SELECT studid FROM fittest group by studid
HAVING Min(prepost)<>max(prepost)

答案 6 :(得分:0)

SELECT 
studid 
FROM `fittest` 
where prepost = 'pre' 
or prepost = 'post'
group by studid
having count(distinct prepost)=2
带有额外记录的

SQL Fiddle

答案 7 :(得分:0)

您可以使用JOIN

SELECT a.studid 
FROM fittest a 
JOIN fittest b 
    ON a.studid=b.studid 
        and a.prepost like 'pre' 
        and b.prepost like 'post'

答案 8 :(得分:-1)

选择.... where studid in(123456,123457,...)