SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    145
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    select from table1 where table1.id is in table2

    Hi there,

    I know there are a few ways to do this, but I'm having a brain fart and I'm unsure what the simplest SQL would be.

    Basically, I have a table of product brands and a table of products. There can be many products to each brand. On my website I only want to display links to brands that actually have products. So I want a simple query that will select the name of each brand whose ID is referenced in the products table.

    Many thanks

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,270
    Mentioned
    60 Post(s)
    Tagged
    3 Thread(s)
    Code:
    SELECT DISTINCT 
           b.name AS brand_name
      FROM brands AS b
    INNER
      JOIN products AS p
        ON p.brand = b.id
    simple, innit
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Zealot
    Join Date
    Jun 2006
    Posts
    145
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfect. Exactly what I thought, but for some reason I was convinced that was a better way than using DISTINCT. Anyway, does the job nicely, thanks

  4. #4
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,270
    Mentioned
    60 Post(s)
    Tagged
    3 Thread(s)
    here's another method
    Code:
    SELECT name AS brand_name
      FROM brands
     WHERE EXISTS
           ( SELECT NULL
               FROM products
              WHERE brand = brands.id )
    you might want to test both (and/or do an EXPLAIN on both) to see which one runs better in your environment
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"


Bookmarks

Posting Permissions

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