SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2005
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Select Statement Help

    I'm having problems with creating a simple SQL select statement.

    The table is as follows
    table - products2features
    fields - prod_id, feature_id
    49 1
    49 3
    49 4
    50 2
    50 5
    51 1
    51 3
    51 6

    The user on the website selects from various features, and I want to determine which single product matches each feature selected. So let say the user selects feaure_id 1 and 3 and 4, I want to return the prod_id, which in this case is 49.

    Here's what I tried,

    SELECT prod_id
    FROM products2features
    WHERE products2features.feature_value_id =1
    AND products2features.feature_value_id =3
    AND products2features.feature_value_id =4

    No results

    SELECT prod_id
    FROM products2features
    WHERE products2features.feature_value_id IN (1,3,4)

    Results
    49
    51

    But I only want the prod_id that matches each of the selected features.

    It seems like it should be so simple, but I guess it too late for my brain to work.

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,251
    Mentioned
    59 Post(s)
    Tagged
    3 Thread(s)
    Code:
    SELECT prod_id
      FROM products2features
     WHERE feature_value_id IN (1,3,4)
    GROUP
        BY prod_id
    HAVING COUNT(*) = 3
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Guru
    Join Date
    Sep 2008
    Posts
    977
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Does that count make sure that the returned product_id matches on three (all three) values in the IN array?

    bazz
    liking the new clock

  4. #4
    From Italy with love silver trophybronze trophy
    guido2004's Avatar
    Join Date
    Sep 2004
    Posts
    9,496
    Mentioned
    163 Post(s)
    Tagged
    4 Thread(s)
    It does if product/feature is the unique key of the table.

  5. #5
    SitePoint Enthusiast
    Join Date
    Oct 2005
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by r937 View Post
    Code:
    SELECT prod_id
      FROM products2features
     WHERE feature_value_id IN (1,3,4)
    GROUP
        BY prod_id
    HAVING COUNT(*) = 3
    Thanks so much, it works perfectly.


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
  •