scarhand
scarhand

Reputation: 4337

combining 2 mysql queries into 1

i am having trouble creating a single mysql query for what i am trying to do here.

first off, i will show you the table structures and fields of the tables i am using for this particular query:

users:
- id
- name
- photo_name
- photo_ext

user_attacks:
- id
- level

user_news_feed:
- id
- id_user
- id_status
- id_attack
- id_profile
- id_wall
- the_date

user_status:
- id
- status

user_wall:
- id
- id_user
- id_poster
- post

whenever the user posts an attack, or status update, updates their profile, or posts on someones wall, it inserts the relevant data into its respective table and also inserts a new row into the user_news_feed table.

now, what i want to do is select the last 10 news feed items from the database. these news feed items need to grab relevant data from other tables as long as their value is not 0. so if the news feed is for a status update, the id_status would be the id of the status update in the user_status table, and the "status" would be the data needing to be selected via a left join. hope that makes sense.

heres my first mysql query:

$sql = mysql_query("select n.id_user, n.id_status, n.id_attack, n.id_profile, n.id_wall, n.the_date, u.id, u.name, u.photo_name, u.photo_ext, s.status
                    from `user_news_feed` as n
                    left join `users` u on (u.id = n.id_user)
                    left join `user_status` s on (s.id = n.id_status)
                    where n.id_user='".$_GET['id']."'
                    order by n.id desc
                    limit 10
                    ");

now this works great, except for 1 problem. as you can see the user_wall table contains the id's for 2 different users. id_user is the user id the post is being made for, and id_poster is the user id of the person making that wall post. if the user makes a wall post on his/her own wall, it is inserted into the database as a status update into the user_status table instead.

so i have a conditional statement within the while loop for the first query, which has another sql query within it. here is the whole code for the while loop and second sql query:

while ($row = mysql_fetch_assoc($sql))
{
    if ($row['id_wall'] != 0)
    {
        $sql_u = mysql_query("select u.id, u.name, u.photo_name, u.photo_ext, w.post
                              from `user_wall` as w
                              left join `users` u on (u.id = w.id_poster)
                              where w.id='".$row['id_wall']."'
                              ");

        while ($row_u = mysql_fetch_assoc($sql_u))
        {
            $row['photo_name'] = $row_u['photo_name'];
            $row['photo_ext'] = $row_u['photo_ext'];
            $row['id_user'] = $row_u['id'];
            $row['name'] = $row_u['name'];
            $content = $row_u['post'];
        }
    }
    else
    {
        if ($row['id_status'] != 0)
            $content = $row['status'];
        else if ($row['id_attack'] != 0)
            $content = '<i>Had an attack</i>';
        else if ($row['id_profile'] != 0)
            $content = '<i>Updated profile</i>';
    }

    echo '<li'.(($count == $total_count) ? ' class="last"' : '').'>';

    echo '<img src="images/profile/'.$row['photo_name'].'_thumb.'.$row['photo_ext'].'" alt="" />';

    echo '<div class="content">';
    echo '<b><a href="profile.php?id='.$row['id_user'].'">'.$row['name'].'</a></b>';
    echo '<span>'.$content.'</span>';
    echo '<small>'.date('F j, Y \a\t g:ia', $row['the_date']).'</small>';
    echo '</div>';

    echo '<div style="clear: both;"></div>';

    echo '</li>';
}

i hope what i am trying to do here makes sense. so basically i want to have both sql queries ($sql, and $sql_u) combined into a single query so i do not have to query the database every single time when the user_news_feed item is a wall post.

any help would be greatly appreciated and i apologise if this is confusing.

Upvotes: 1

Views: 160

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753725

SELECT n.id_user, n.id_status, n.id_attack, n.id_profile, n.id_wall, n.the_date,
       u.id, u.name, u.photo_name, u.photo_ext, s.status,
       w.id AS wall_user_id, w.name AS wall_user_name,
       w.photo_name AS wall_user_photo_name,
       w.photo_ext  AS wall_user_photo_ext,
       w.post
  FROM user_news_feed AS n
  LEFT JOIN users AS u ON (u.id = n.id_user)
  LEFT JOIN user_status s ON (s.id = n.id_status)
  LEFT JOIN (SELECT a.id AS id_wall, b.id, b.name, b.photo_name, b.photo_ext, a.post
               FROM user_wall  AS a
               LEFT JOIN users AS b ON (b.id = a.id_poster)
            ) AS w ON w.id_wall = n.id_wall
 WHERE n.id_user = ?
 ORDER BY n.id desc
 LIMIT 10

The '?' is a placeholder where you can provide the value of $_GET['id'].

Basically, this adds an extra outer join, to the main query (and some extra columns, which will be NULL if the news feed event is not a wall posting), but the outer join is itself the result of an outer join.

Upvotes: 2

Andreas
Andreas

Reputation: 2266

Back again ;)

Anyway, forget about merging the queries in my opinion.

What you should do instead is to do the first query, loop through all the results and store all "id_wall"s in a separate array... then rather than doing a separate query per "id_wall" you do this:

$wallids = array();
while ($row = mysql_fetch_assoc($sql)) 
{ 
    $wallids[] = $row['id_wall'];
    // also store the row wherever you want
}

$sql_u = mysql_query("select u.id, u.name, u.photo_name, u.photo_ext, w.post    
                      from `user_wall` as w    
                      left join `users` u on (u.id = w.id_poster)    
                      where w.id IN ('".implode(',', $wallids) ."')    
                      ");

$wallids being an array with all the "id_wall"s. So now you have a total of 2 queries.

Upvotes: 0

Related Questions