开发者

conditional query mysql

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.


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.


This should work:

SELECT c.PageId,c.UserId, m.UserName FROM Members as m
INNER JOIN Comments as c
ON m.UserId = c.UserId
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜