开发者

conditional query mysql

开发者 https://www.devze.com 2023-01-20 09:39 出处:网络
i have this mysql schema: comments: ----------------------------- |id|pageid|userid| members: -----------------------------

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

精彩评论

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

关注公众号