Jump to content

SELECT DISTINCT returning duplicates


kirkh34

Recommended Posts

Hello. I have a table title_views with each row being a "view" with a user_id, title_id, prog_id, date, and id. I want to gather just the user_ids without it returning duplicate user_ids. Right now I'm receiving duplicate user_id. Any help is appreciated. Thank you.

 

<?PHP 
include("db.php"); 

   $qry= mysql_query("SELECT * FROM programs")
or die (mysql_error());

while($row = mysql_fetch_array($qry)){

$prog_titles = $row['titles'];
$prog_titles = explode(',' , $prog_titles);
$prog_id = $row['prog_id'];

array_shift($prog_titles); 
                    
                    foreach($prog_titles as $prog_title){
                        
                    $trimmed = trim($prog_title); 
       
                    $qry= mysql_query("SELECT DISTINCT user_id FROM title_views WHERE title_id = '$trimmed' and prog_id = '$prog_id'  ")
                    or die(mysql_error());
                    $row = mysql_fetch_array($qry);
                    
                    echo $row['user_id'] . "<br />";
                     
                    }  // end foreach

                    } //end while

?>

Link to comment
Share on other sites

I guess a better description of what the OP wants would help.

DISTINCT will return only unique results over all of your selected columns combined.

OP only selected user_id, so it would work that way except he's running the query for every title, so he's going to get each user for each title.

Link to comment
Share on other sites

thank you for your replies.  I understand that it is wrong to run queries in loops, but I am not sure how I would complete it otherwise? I have to run that foreach loop in order to get the title_id needed to run the query.  Can you explain a different structure that would work for what I need?

Link to comment
Share on other sites

By using a comma-delimited list in your table, you've made it very difficult to query against data within that list.

 

You're going to want to normalize that data, give each comma delimited item it's own row that references back to a specific program.

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.