SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Thread: SQL Question

  1. #1
    SitePoint Addict
    Join Date
    Oct 2003
    Location
    Tenerife, Spain / UK
    Posts
    329
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    SQL Question

    SQL Question

    Tables

    Products
    ProductID PK
    Description
    Price

    Photos
    PhotoID PK
    PhotoPath 'URL of the photo on the web server
    Product ID FK

    A one-to-many relationship exists between the Products table and the photos table, ie: each product can have 0, 1, 2, 3 or more photos associated with it.

    How can you perform a query which lists all products and only the first corresponding photo path, yet provides a default values for the Photopath so an "Awaiting Image" can be displayed if there not yet a photo record associated with the product.

    I could solve this with a nested query, but that's messy.

    NB: Access SQL appreciated.
    David Parkes
    Nuclear Internet - Windows Web Hosting
    http://www.nuclearinternet.com

  2. #2
    SitePoint Enthusiast
    Join Date
    Sep 2004
    Location
    Blackpool, UK
    Posts
    67
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't have much time, but wanted to try and help - it's something like this: (ISNULL works in SQL Server, not sure about Access):

    SELECT [Products].ProductID, [Products].Description, [Products].Price, ISNULL([Photos].[PhotoPath],'AwaitPhoto.jpg') AS [PhotoPath] FROM [Products] LEFT OUTER JOIN [Photos] ON [Photos].[ProductID] = [Products].[ProductID] AND [Photos].[PhotoID] = (SELECT TOP 1 PhotoID FROM [Photos] WHERE [Photos].[ProductID] = [Products].[ProductID])
    dt digital : internet design & consultancy

  3. #3
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,218
    Mentioned
    58 Post(s)
    Tagged
    3 Thread(s)
    Code:
    SELECT Pro.ProductID
         , Pro.Description
         , Pro.Price
         , IIF( Pho.PhotoPath IS NULL
              , 'AwaitPhoto.jpg'
              , Pho.PhotoPath ) AS PhotoPath 
      FROM Products as Pro
    LEFT OUTER 
      JOIN Photos as Pho
        ON (
           Pho.ProductID = Pro.ProductID 
       AND Pho.PhotoID = 
           ( SELECT MIN(PhotoID)
               FROM Photos 
              WHERE ProductID = Pro.ProductID )
           )
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  4. #4
    SitePoint Member
    Join Date
    Jul 2007
    Posts
    4
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try google for a tutorial


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
  •