MySQL: conditions for table2 of LEFT JOIN

Discussion in 'PHP' started by Hade, Apr 30, 2008.

  1. #1
    Hi,
    This isn't strictly PHP, but this is the best forum for it.


    I'm trying to perform a LEFT JOIN, while restricting the rows from the second table.

    Basically, I want all rows from the first table, plus ones with a corresponding field in table 2. I ONLY want rows from table 2 to be added if id='1' for example.

    Adding a {WHERE table2.id='1'} restricts the whole query, only showing rows where the WHERE condition is met. I just want it to restrict what rows from table 2 are used.

    I hope I'm being clear enough! If I'm not, I'll try and give an example.
     
    Hade, Apr 30, 2008 IP
  2. Altari

    Altari Peon

    Messages:
    188
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Could you post the entire query? There are several things I can think of by just that description, so the whole thing would really nail things down.
     
    Altari, Apr 30, 2008 IP
  3. Hade

    Hade Active Member

    Messages:
    701
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    90
    #3
    == Categories ==
    category_id
    category_name

    == Products_to_categories ==
    products_to_categories_id
    product_id
    category_id


    == Products ==
    product_id
    category_id
    product_name




    I want to retrieve all categories, and I want to know if a paticular product with product_id=5 is within that category.

    Ultimately, I want a list of checkboxes for all categories, with the relevant ones ticked if the product is in that category (a product can be in multiple categories)

    THANK YOU!!!
     
    Hade, Apr 30, 2008 IP
  4. Altari

    Altari Peon

    Messages:
    188
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #4
    My husband took a look...he suggests something along these lines. He said "that should do the trick assuming they're using MySQL 5".

    select cat.category_id, cat.category_id, (select COUNT(*) from products_to_categories ptc where ptc.category_id = cat.category_id and ptc.product_id = 5) product_five_in_this_category from categories cat;
     
    Altari, Apr 30, 2008 IP
  5. Hade

    Hade Active Member

    Messages:
    701
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    90
    #5
    Thank you very much for taking the time to reply.
    I will give it a go in the morning and let you know how I get on...
     
    Hade, Apr 30, 2008 IP
  6. Hade

    Hade Active Member

    Messages:
    701
    Likes Received:
    18
    Best Answers:
    0
    Trophy Points:
    90
    #6
    Bingo! A perfect solution. Thank you very much to both you and your husband.
     
    Hade, May 1, 2008 IP