LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   MySQL - Query and compare 2 tables (http://www.linuxquestions.org/questions/programming-9/mysql-query-and-compare-2-tables-641606/)

rookiepaul 05-12-2008 05:14 AM

MySQL - Query and compare 2 tables
 
Hi Guys,

I have two tables in a mysql database: Subscribers and Unsubscribers. Subscribers is a table containing the details of everyone who signs up for our newsletters (email address, name etc). When people sign up for our website they're details are placed in subscribers. When people unsubscribe they're details go into unsubscribers. It's a stupid system. If I have built the system I would have had a binary unsubscribed field in the subscriber table set to one if they choose to unsubscribe. But what this means is that when I want a list of all currently subscribed people, I need to compare the two tables and pull out the details of all the people who appear in the subscribers table but not the unsubscribers table. This is where I fall down. I'm pretty good with standard queries but I've never compared 2. If I was able to use PHP I would write a loop to do this but I have to do this at the command line so I'm stuck. Can anyone help. Much appreciated.

acid_kewpie 05-12-2008 05:50 AM

a nested statement is probably the simplest logic to use, not the most elegant, but for a one off...

Code:

select username from subscribers users where username not in (select username from unsubscribers)
alternatively a left join would be more technically correct...

Code:

select subscribers.username from subscribers left join unsubscribers where unsubscribers.username is null

rookiepaul 05-12-2008 06:31 AM

They didn't seem to work. I'm not sure I was clear on what I needed.

I need the EmailAddress of all the users in Subscribers who's NotifyServices field = 1 and who's EmailAddress is NOT in the Unsubscribers table. Sorry for the confusion.

Many thanks.

acid_kewpie 05-12-2008 06:44 AM

OK, well it's only an example, i'm sure you can add in those extra clauses...


select emailaddress from subscribers users where username not in (select username from unsubscribers) and NotifyServices = 1

rookiepaul 05-12-2008 09:05 AM

Ok, I finally got it working, but the query is a bit different to the one that you suggested.

Code:

SELECT Subscribers.EmailAddress, Subscribers.NotifyServices, Subscribers.SubscriberID FROM AlertSystem.Subscribers Subscribers WHERE (Subscribers.NotifyServices = 1) AND (Subscribers.SubscriberID NOT IN (SELECT DISTINCT CancelledSubscribers.SubscriberID FROM AlertSystem.CancelledSubscribers CancelledSubscribers));
Thanks for the help.

Paul.


All times are GMT -5. The time now is 08:47 PM.