Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2

Thread: Field Linking

  1. #1
    Regular Coder
    Join Date
    Mar 2009
    Posts
    120
    Thanks
    13
    Thanked 3 Times in 3 Posts

    Field Linking

    Awright, there's this table called 'users':

    |user_id|name|password|

    Ok, now, there's the table 'news':

    |news_id|user_id|news|

    What I'd like to do is to link this 'user_id' with the 'user_id' from the other table. What's the best method for doing this?

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,189
    Thanks
    75
    Thanked 4,341 Times in 4,307 Posts
    Depends on what you want to do with the result.

    If all you want to do is get all the related fields from both tables:
    Code:
    SELECT U.user_id, U.name, U.`password`,N.news_id,N.news
    FROM `users` AS U, news AS N
    WHERE U.user_id = N.user_id
    ORDER BY U.name, N.news_id
    If you need *all* users, even if they don't HAVE any records in the news table, you have to use a LEFT JOIN:
    Code:
    SELECT U.user_id, U.name, U.`password`,N.news_id,N.news
    FROM `users` AS U LEFT JOIN news AS N ON U.user_id = N.user_id
    ORDER BY U.name, N.news_id


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •