Querying Using Foreign Keys

Discussion in 'PHP' started by Horus7, Jul 9, 2007.

  1. #1
    Hi, I'm not sure how I would query my DB with the use of the keys.
    My table will reference the username column in another table.
    The question is, can I call on the username column through the foreign key?
     
    Horus7, Jul 9, 2007 IP
  2. ansi

    ansi Well-Known Member

    Messages:
    1,483
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    100
    #2
    a foreign key basically just ensures a relation between two the data of two tables. in other words, you can't have one without the other. if one doesn't exists, the query will fail. you would need a join to access the the data on the related table.

    in my example we have two tables. tbl1 and tbl2. tbl1 has 2 columns, tbl1.id and tbl1.foo while tbl2 has 2 columns.. tbl2.id and tbl2.bar
    so basically this is saying select tbl2.bar where tbl2.bar = 'something' and then using the tbl2.id return tbl1.foo with the related id.

    
    select foo, bar from tbl1 left join tbl2 on tbl2.id = tbl1.id where tbl2.bar = 'something'
    
    Code (markup):
     
    ansi, Jul 9, 2007 IP
  3. Horus7

    Horus7 Peon

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    So, even if I establish a primary key in one table, and reference it with
    a foreign key in another table, I still have to create a join between the tables,
    to access their columns respectively?

    I mean, I can't just set up a primary key, and use the foreign key, to acces that tables data?
     
    Horus7, Jul 10, 2007 IP
  4. ansi

    ansi Well-Known Member

    Messages:
    1,483
    Likes Received:
    65
    Best Answers:
    0
    Trophy Points:
    100
    #4
    nope. the key is just used for normalization of relational tables.
     
    ansi, Jul 10, 2007 IP
  5. Horus7

    Horus7 Peon

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Ok thanks, but do these temp tables last only as long as the connection or what?
    Also can I join 2 tables that do not have a matching column?
    And, how do I call on the temporary table, so that I can run a query on it?
     
    Horus7, Jul 12, 2007 IP