Domanda

I have three different tables - subscribers, unsubscribers, mass subscribers.

I'd like to print out each email from the mass subscribers table. However that email can only be printed if it doesn't exist in both subscribers and unsubscribers tables.

I know how to do this with arrays, however I want a plain mysql query.

What would mysql query be?

Thanks!

È stato utile?

Soluzione

You can do that with a subquery (this is slow! Please read below the line):

SELECT email 
FROM subscribers 
WHERE email NOT IN(SELECT email FROM unsubscribers)

However, this is very bad for performance. I suggest you change the way you have your database, with just 1 table subscribers, and add a column active(tinyint). When someone unsubscribes, you set that value from 1 to 0. After that you can stay in 1 table:

SELECT email FROM subscribers WHERE active=1

This is faster because of some reasons:

  • No subquery
  • The where is bad, because you are going to select a heap of data, and compare strings
  • Selecting on integer in VERY fast (especially when you index it)

Apart from the fact that this is faster, it would be better for your database structure. You dont want two tables doing almost the same, with emailadresses. This will create duplicate data and a chance for misalignments

Altri suggerimenti

You sound like someone who doesn't have much experience with SQL. Your title does point in the right direction. Here is how you put the components together:

select m.*
from mass_subscribers m
where not exists (select 1 from subscribers s where s.email = m.email) and
      not exists (select 1 from unsubscribers u where u.email = m.email);

NOT EXISTS happens to be a very good choice for this type of query; it is typically pretty efficient in both MySQL and other databases.

Without subqueries, using join

SELECT mass_subscribers.*
FROM mass_subscribers ms
LEFT JOIN subscribers s ON ms.email=s.email
LEFT JOIN unsubscribers us ON us.email=s.email
WHERE
ms.email IS NULL
AND
us.email IS NULL
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top