Forum Moderators: coopster

Message Too Old, No Replies

Select unique entries with SQL joins or with PHP?

         

andrewheiss

8:59 pm on Jul 7, 2008 (gmt 0)

10+ Year Member



I'm not sure if this should go here or in the database forum...

I have three tables in a MySQL database that I'm going to use to send mass e-mails: emails, lists, and emails_lists (a bridge table with foreign keys).

A person can be subscribed to any number of lists and a message can be sent to any number of lists as well. I have PHP collect the lists in an array variable behind checkboxes (with a name of list[]) and then implode the array to a comma-separated list.

I can easily select a join of the email addresses and the selected lists.


$lists = $_POST['lists'];
$fk_list = implode(",",$lists);
$query = "SELECT * FROM emails LEFT JOIN emails_lists ON emails.id_email = emails_lists.fk_email WHERE email_valid = 1 AND fk_list IN ($fk_list)";

I can then iterate through that result and send off the e-mails. However, if someone is signed up for multiple lists, their record gets selected multiple times, leading to duplicate e-mails.

What's the best way to eliminate duplicate instances of emails.id_email in the SELECT? Is there an SQL way or should I use PHP to manage and keep track of the uniqueness of the entries? If PHP is the only solution, how would I go about doing that?

Thanks!

andrewheiss

9:17 pm on Jul 7, 2008 (gmt 0)

10+ Year Member



After more googling, I think I discovered it. SELECT DISTINCT does exactly what I need:


SELECT DISTINCT(id_email), email_name, email FROM emails LEFT JOIN emails_lists ON emails.id_email = emails_lists.fk_email WHERE email_valid = 1 AND fk_list IN ($fk_list)