views:

43

answers:

2

hi, i have this mysql schema:

comments:
    -----------------------------
    |id|pageid|userid|

members:
    -----------------------------
    |username|userid|

sometimes the userid from comments is blank, cause anon comment. how i can get the username from members if userid from comments isn't blank.

i need to get something like this:

---------------------------
|id|pageid|userid|username|
---------------------------

Edit. i want to try to be more specific.

comments:
    ----------------------------------
    |id|pageid|userid|comment        |   
    ---------------------------------- 
    |1 |1     |1     | hi            |
    ---------------------------------- 
    |2 |1     |      | annon comment |

members:
    -----------------------------
    |username|userid            |
    -----------------------------
    |john    |1                 |

thats is a example data, now i need to get something like this:

    -------------------------------------------
    |id|pageid|userid|comment        |username|  
    ------------------------------------------- 
    |1 |1     |1     | hi            |john    |
    ------------------------------------------- 
    |2 |1     |      | annon comment |        |

ps sorry for my bad english.

+1  A: 

This should work:

SELECT c.PageId,c.UserId, m.UserName FROM Members as m
INNER JOIN Comments as c
ON m.UserId = c.UserId
Abe Miessler
if the userid from comments table is blank all these anonymous comments are ignored.
greenbandit
Yes, based on your statement `how i can get the username from members if userid from comments isn't blank.` this would be the correct behavior...
Abe Miessler
+1  A: 
SELECT c.PageId,c.UserId, m.UserName FROM comments as c
LEFT OUTER JOIN members m ON c.userid = m.userid

LEFT JOIN gets you fields that do not have a match in the right table.

gms8994
thanks, this is now working.
greenbandit