1

I would like to create a query to insert several values along with values that come from other tables, for example:

INSERT INTO table
(date, user_id, category_id, title, description)
VALUES
    ((STR_TO_DATE('04-01-2014', '%b-%d-%Y'), 
    (SELECT id FROM users WHERE username = 'admin' LIMIT 1),
    (SELECT id FROM categories WHERE category = 'games' LIMIT 1),
    'title here',
    'description here')

This however, gives me an error and from PHP a 500 internal server error. Help please.

2 Answers 2

1
INSERT INTO table (fields)
SELECT
    str_to_date(),
    users.id,
    categories.id,
    'title',
    'description' 
FROM
    users 
INNER JOIN
    categories ON users.key = categories.key
WHERE
    users.username = 'admin' AND
    categories.category = 'games'

that should do it I think...

Sign up to request clarification or add additional context in comments.

2 Comments

Works great only problem is date is not being inserted, any thoughts?
Will do, thank you. I would vote you up but don't have enough points.
0

I'm pretty sure you need a SELECT after VALUES if you're doing it this way. Try this and see if it works.

INSERT INTO table
(date, user_id, category_id, title, description)
VALUES
SELECT 
  STR_TO_DATE('04-01-2014', '%b-%d-%Y'), 
  (SELECT id FROM users WHERE username = 'admin' LIMIT 1),
  (SELECT id FROM categories WHERE category = 'games' LIMIT 1),
  'title here',
  'description here'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.