0

I have got 2 tables

pages

page_id   post_id   pid  
 3421      2345      1357 
 3421      4567      2468
 3421      7891      1357

usrs

 pid      fname    lname 
 1357     john     bravo
 2468     ray      mexy

Using the below statement

$result = mysql_query("SELECT usrs.*,pages.* FROM usrs INNER JOIN pages ON 

 usrs.pid = pages.pid WHERE pages.page_id = '$pageid'"); // $pageid = 3421

It gives all the matches of page_id = 3421 in the form of array.

Something like this will echo the result

     while($row = mysql_fetch_array($result))
        echo $row['post_id'] . " " . $row['fname'] . " " . $row['lname'];

o/p is   2345 john bravo 
         4567 ray  mexy
         7891 john bravo

Now the real question is, I have got another table to work on in this case

Consider table 3 : total_likes

   post_id   pid
    2345     3214
    2345     4123
    1245     4567
    2345     2367

users got the choice to like it and when user hits the like button hes pid is added with the post_id and now I want the number of likes for the specific post_id that is the number of rows for the specific post_id.

I want output to be something like this

         2345 john bravo     45 likes
         4567 ray  mexy      32 likes
         1357 john bravo     20 likes 

I am not sure if its possible or not, since third table holds more values for post_id . It's like an array of value pointing to a value of an array $row['post_id'].

4

1 回答 1

1

您可以有一个额外的子查询,分别计算每个post_id.

SELECT  a.*, 
        b.*
        c.likes, c.IsExist
FROM    pages a
        INNER JOIN usrs b
            ON a.pid = b.pid
        LEFT JOIN
        (
            SELECT  post_id, 
                    COUNT(*) likes,
                    IF(SUM(pid = 1357) > 0, 'yes', 'no') IsExist
            FROM    total_likes
            GROUP   BY post_id
        ) c ON b.post_id = c.post_id
WHERE   a.page_id = 3421
于 2013-07-20T17:41:30.947 回答