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 6 of 6
  1. #1
    Regular Coder
    Join Date
    Jun 2004
    Posts
    130
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Selecting from two tables

    This is really a stupid question but i just can't think today lol.

    i got two tables, let's say
    tbl1
    -----
    id
    title
    id2
    ----

    tbl2
    ----
    id
    title
    id2
    ----

    Now i need to know if there's data in either tables with id2 is let's say 5

    SELECT * FROM `tbl1`, `tbl2` WHERE `tbl1`.`id2` = '5' OR `tbl2`.`id2` = '5';

    won't work.
    quite logical, but again, i can't think today.
    can anyone help?

  • #2
    Super Moderator guelphdad's Avatar
    Join Date
    Mar 2006
    Location
    St. Catharines, Ontario Canada
    Posts
    2,634
    Thanks
    4
    Thanked 148 Times in 139 Posts
    You want a UNION or UNION ALL.

    UNION will give you results from the two tables but eliminate duplicate rows, the UNION ALL will return both tables, duplicates included.

    Code:
    select
    id,
    title,
    id2
    FROM table1
    where id2 = 5
    UNION ALL
    select
    id,
    title,
    id2
    FROM table2
    where id2 = 5

  • #3
    Regular Coder
    Join Date
    Jun 2004
    Posts
    130
    Thanks
    0
    Thanked 0 Times in 0 Posts
    thnx m8 that did the trick

  • #4
    Super Moderator guelphdad's Avatar
    Join Date
    Mar 2006
    Location
    St. Catharines, Ontario Canada
    Posts
    2,634
    Thanks
    4
    Thanked 148 Times in 139 Posts
    oh and one last thing, in case you need to know what table the results came from you can use this trick:

    Code:
    select
    'table 1' as tablename,
    id,
    title,
    id2
    FROM table1
    where id2 = 5
    UNION ALL
    select
    'table 2',
    id,
    title,
    id2
    FROM table2
    where id2 = 5

  • #5
    Regular Coder
    Join Date
    Jun 2004
    Posts
    130
    Thanks
    0
    Thanked 0 Times in 0 Posts
    thnx m8

    didnt need to know that though, there were two categories having there own table in which users could place records, but in one of the two categories a categorie-title had to be made first.

    but thnx

  • #6
    Super Moderator guelphdad's Avatar
    Join Date
    Mar 2006
    Location
    St. Catharines, Ontario Canada
    Posts
    2,634
    Thanks
    4
    Thanked 148 Times in 139 Posts
    You should have a single table in my opinion with either NULL or a default value for the category title.


  •  

    Posting Permissions

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