Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL - SELECT from multiple rows, same user, different values

Tags:

mysql

Below is my table called fittest. I need to find which students based on student id (studid) have taken the pre and post test as designated in the prepost column. So based on the simple table below I would need to return studid 123456. How do I write the SELECT query for this?

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

    studid  prepost
    123456  pre
    123456  post
    1031460 pre
like image 539
user2609500 Avatar asked Jul 23 '13 07:07

user2609500


People also ask

How do I select multiple records in mysql?

To select multiple values, you can use where clause with OR and IN operator.

What is the difference between select * and select?

Save this answer. Show activity on this post. select * will return values for all the columns in the table that have rows that match your predicate, while select column_name will only return the values in the column_name column for the rows that match your predicate. Save this answer.

How do I select all rows except one?

Select the header or the first row of your list and press Shift + Ctrl + ↓(the drop down button), then the list has been selected except the first row.


2 Answers

Try

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

or if you want to ensure that only ids that have exactly one row with pre and one row with post then you can enforce it like this

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

Output:

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

Here is SQLFiddle demo for both queries

like image 194
peterm Avatar answered Oct 04 '22 14:10

peterm


What about a 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'
like image 28
CodeZombie Avatar answered Oct 04 '22 14:10

CodeZombie