Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

MySql join

Options
  • 10-01-2008 6:46pm
    #1
    Registered Users Posts: 302 ✭✭


    I am a novice sql user & cant figure out how to do the following in MySql sql (or any other sql for that matter);

    Product
    id
    name

    Order
    id
    prod_id (f/key)
    qty

    I want to return the list of products that do not have orders against them.


Comments

  • Registered Users Posts: 23,212 ✭✭✭✭Tom Dunne


    What have you tried? :)


  • Registered Users Posts: 302 ✭✭BlueSpud


    Well thats my problem, I dont know how to begin to express the problem, never mind try something.

    My knowlege extends only to joining A and B, C, D with inner & left joins and a where clause.


  • Registered Users Posts: 981 ✭✭✭fasty


    You don't need to do a join per se. Think about what you want...

    You want all products that are not in the orders table. Your where clause can be a sub query.


  • Registered Users Posts: 302 ✭✭BlueSpud


    Just got the following to work(plagerised from the web). I understand that it is more efficient than the subquery, or so the article says.

    SELECT p.id, p.name
    FROM prod p
    LEFT JOIN ord AS o ON o.prod_id = p.id
    WHERE o.prod_id IS NULL


  • Registered Users Posts: 610 ✭✭✭nialo


    Alternative way of doing it. What you have is fine too thou..

    select p.id, p.name from Product p where p.id not in (select distinct prod_id from Orders)


  • Advertisement
  • Registered Users Posts: 302 ✭✭BlueSpud


    The reason I struggled for so long to get it working was that I was using
    blah = null
    and not
    blah is null

    Thanks for the help.


  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    BlueSpud wrote: »
    The reason I struggled for so long to get it working was that I was using
    blah = null
    and not
    blah is null

    Thanks for the help.
    Yeah, NULL is a special state in most databases. It's not a value, in fact it specifically means "Has no value". This differs from having a blank in the database, which does in fact have a value, it's just blank. So you can't check if something is equal to NULL (because NULL is not a value), you can only check if it is in the NULL state.

    If you start using a scripting language like PHP, it'll screw with your head when you find out that PHP treats NULL and blank as the same thing when you're reading the database data. :)


Advertisement