Results 1 to 14 of 14

Thread: [RESOLVED] Difficult nested SELECT within an INSERT statement

Threaded View

  1. #1

    Thread Starter
    No place like 127.0.0.1 eyeRmonkey's Avatar
    Join Date
    Jul 2005
    Location
    Blissful Oblivion
    Posts
    2,306

    Resolved [RESOLVED] Difficult nested SELECT within an INSERT statement

    From everything I've read, I don't think this is possible, but here is the statement I am trying to achieve:

    My columns: primary_key, name, name_based_id
    Code:
    INSERT IGNORE INTO artists (primary_key, name, name_based_id) VALUES 
    ('10:w9ftxqe5ldhe', 'Joe', (SELECT COUNT(*) FROM artists WHERE name='Joe')), 
    ('11:jifuxqr5ldh', 'Bob', (SELECT COUNT(*) FROM artists WHERE name='Bob')),
    ('22:a9ftx34gldae', 'Joe', (SELECT COUNT(*) FROM artists WHERE name='Joe')), 
    ...
    Basically, every time I add an artist, I want the name_based_id to be equal to the number of artists already present in the database with that name.

    It would result in something like so:
    '10:w9ftxqe5ldhe', 'Joe', 0
    '11:jifuxqr5ldh', 'Bob', 0
    '22:a9ftx34gldae', 'Joe', 1

    The third row is "Joe 1" because he was the second joe added to the database.

    From what I've read, you can't do a nested SELECT from the same table you're inserting into.

    Is there anyone to accomplish this in one query?

    I'd even settle for multiple queries, as long as it got the job done.

    If I didn't clarify it enough, please let me know. I really need some assistance on this.

    Thanks.

    Note: I'm using MySQL 5.0. I'm working with an InnoDB engine. I'm writing this all in PHP, but I don't think that matters for this question.
    Last edited by eyeRmonkey; Jul 20th, 2007 at 05:11 AM.
    Visual Studio 2005 Professional Edition (.NET Framework 2.0)
    ~ VB .NET Links: Visual Basic 6 to .NET Function Equivalents (Thread) | Refactor! (White Paper) | Easy Control for Wizard Forms | Making A Proper UI For WinForms | Graphics & GDI+ Tutorial | Websites For Free Icons
    ~ QUOTE: Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. -Rich Cook

    ~ eyeRmonkey.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width