SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict
    Join Date
    Oct 2009
    Location
    London, UK
    Posts
    382
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)

    Question INSERT SELECT statement

    Hi there,

    I having a problem with a MySQL INSERT .. SELECT statement:
    Code:
    INSERT INTO
    `products`
    (
      `id`, 
      `image`, 
      `title`, 
      `description`, 
      `price`, 
      `VAT`, 
      `related_products`
    ) 
    SELECT 
      'CR25', 
      `id` FROM `images` WHERE `images`.`title` = 'Some Image Title', 
      'Product Title', 
      'Product Description', 
      4.99, 
      0, 
      'CR26'
    Throws an error:
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 'Product Title'

    I've also tried
    Code:
    INSERT INTO
    `products`
    (
      `id`, 
      `image`, 
      `title`, 
      `description`, 
      `price`, 
      `VAT`, 
      `related_products`
    ) 
    VALUES
    ( 
      'CR25', 
      (`id` FROM `images` WHERE `images`.`title` = 'Some Image Title'), 
      'Product Title', 
      'Product Description', 
      4.99, 
      0, 
      'CR26'
    )
    But I get a similar error message:
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '

    As far as I can tell I'm using the correct syntax.

    Any ideas?

    Cheers
    M

  2. #2
    SQL Consultant gold trophysilver trophybronze trophy
    r937's Avatar
    Join Date
    Jul 2002
    Location
    Toronto, Canada
    Posts
    39,273
    Mentioned
    60 Post(s)
    Tagged
    3 Thread(s)
    Quote Originally Posted by mickyginger View Post
    As far as I can tell I'm using the correct syntax.
    almost, but not quite

    all the constant values (strings, numbers) should be included in the SELECT clause...
    Code:
    INSERT 
      INTO products
         ( id
         , image
         , title
         , description
         , price
         , VAT
         , related_products ) 
    SELECT 'CR25'
         , id 
         , 'Product Title'
         , 'Product Description'
         , 4.99
         , 0
         , 'CR26'
      FROM images 
     WHERE title = 'Some Image Title'
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL
    "giving out my real stuffs"

  3. #3
    SitePoint Addict
    Join Date
    Oct 2009
    Location
    London, UK
    Posts
    382
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    As always r937, worked like a charm! Many thanks!

    M


Tags for this Thread

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
  •