S
S
SkyAleks2011-11-12 15:36:28
MySQL
SkyAleks, 2011-11-12 15:36:28

Create a select query (mysql)

Help make a request.
There is a mails table in which there are two fields email and status
The table has 5 rows

Email1 status1
Email2 status1
Email3 status1
Email1 status2
Email2 status2


That is, as we can see, Email1 and Email2 have two records with different statuses.
We need to create a query that would make a selection from this table and return us only emails with status 1, which are not in the table with status 2.
That is, in our case, this would be the only record - Email3

Answer the question

In order to leave comments, you need to log in

5 answer(s)
I
Ivan Komarov, 2011-11-12
@FreeTibet


SELECT m1.*
FROM mails AS m1
LEFT JOIN mails AS m2 
  ON m1.email = m2.email AND m2.`status` = 'status2'
WHERE 
  m1.`status` = 'status1' 
  AND m2.email IS NULL

I
Ivan Komarov, 2011-11-12
@FreeTibet

And here is a little perversion for which we all love SQL so much:


SELECT email, `status` FROM (
  SELECT email, `status`, COUNT(*) AS cnt 
  FROM mails 
  GROUP BY email
  HAVING `status` IN ('status1', 'status2')
) AS subq WHERE cnt = 1;

E
ertaquo, 2011-11-12
@ertaquo

Something like this:
SELECT * FROM table WHERE email NOT IN (SELECT email FROM table WHERE email NOT LIKE "status2")

M
mark_ablov, 2011-11-12
@mark_ablov

select email from t where email not in (select email from t where status = 'status2') and status = 'status1'
But this is clumsy, think about database architecture or logic.

I
Ivan Komarov, 2011-11-12
@FreeTibet


SELECT m1.* FROM mails AS m1 
WHERE NOT EXISTS(
  SELECT * FROM mails AS m2 
  WHERE 
    m2.email = m1.email AND m2.`status` = 'status2'
)

But the first option is prettier.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question