Jump to content

selecting user info if 2 rows in mysql exist


unistake
Go to solution Solved by Jacques1,

Recommended Posts

Hi all,

 

I am trying to make a list of users where two rows in a mysql database exist.

 

My attempt so far: 

"SELECT * FROM mail_list INNER JOIN rosters ON mail_list.Code = rosters.Code WHERE rosters.SectorDate = '2016-01-04' AND EXISTS (SELECT * FROM rosters WHERE rosters.SectorDate = '2016-01-24' IS NOT NULL)"

 

So basically, I want to select all the users information from mail_list table only if in the rosters table the user has a row that exists with the date 2016-01-04 and a second row 2016-01-24.

 

I have tried several types of EXIST statements as above but no luck so far :/

 

Please help!!

 

Thanks

Link to comment
Share on other sites

I, preferring to avoid subqueries whenever possible, would do two JOINs

SELECT ml.*
FROM mail_list ml
JOIN rosters r1 ON ml.Code = r1.Code AND r1.SectorDate = '2016-01-04'
JOIN rosters r2 ON ml.Code = r2.Code AND r2.SectorDate = '2016-01-24'
unless there are multiple rows in rosters for each Code/SectorDate pair...
  • Like 1
Link to comment
Share on other sites

  • Solution


SELECT
-- select concrete columns, not just "*"
FROM
mail_list
JOIN rosters USING (Code)
WHERE
rosters.SectorDate IN ('2016-01-04', '2016-01-24')
GROUP BY
-- repeat all the columns from the SELECT part
HAVING
COUNT(DISTINCT rosters.SectorDate) = 2
;

 

Edited by Jacques1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.