0

I can't get the mysql syntax correct. I would like to insert into a table 2 pieces of data, post_id and meta_value from another table on the same database and todays date, CURDATE()) .

INSERT into wp_top_voted  

(post_id, number_votes, todays_date)

The following:

SELECT `post_id`  
FROM  `wp_postmeta` WHERE  `meta_key` =  'votes' ORDER BY  `meta_value` DESC   
LIMIT 10
SELECT `meta_value`  
FROM  `wp_postmeta` WHERE  `meta_key` =  'votes' ORDER BY  `meta_value` DESC   
LIMIT 10
CURDATE()) 

How do I combine the above into one statment? I tried

INSERT into wp_top_voted  
(`post_id`, `number_votes`, `todays_date`)  
values (SELECT `post_id`  
FROM  `wp_postmeta` WHERE  `meta_key` =  'votes' ORDER BY  `meta_value` DESC   
LIMIT 10, SELECT `meta_value`  
FROM  `wp_postmeta` WHERE  `meta_key` =  'votes' ORDER BY  `meta_value` DESC   
LIMIT 10,   CURDATE()) 

but I'm getting errors.

4
  • Can you add sample data and the expected result please? Commented Mar 16, 2015 at 10:40
  • Try to JOIN the source tables Commented Mar 16, 2015 at 10:42
  • beside the solution suggested by me , you may also want to check for the ' character you used, they seems different to me Commented Mar 16, 2015 at 10:47
  • I think when you insert multiple rows into table VALUES part of statement inside the parentheses also need do be separated by parentheses INSERT INTO(colum1, colum2) VALUES((val1, val2, val3), (val4, val5, val6)) etc... in your case instead of val1, val2, val3 you have SELECT statement like VALUES((SELECT statement1), (SELECT statemet 2)).. Commented Mar 16, 2015 at 11:25

2 Answers 2

1

You are getting error because of incorrect format of INSERT INTO TABLE() SELECT. Try this:

INSERT into wp_top_voted  
(`post_id`, `number_votes`, `todays_date`)  
SELECT `post_id`, `meta_value`, CURDATE() 
FROM  `wp_postmeta` WHERE  `meta_key` =  'votes' ORDER BY  `meta_value` DESC   
LIMIT 10;
Sign up to request clarification or add additional context in comments.

Comments

1

You can find a pretty good explanation here http://www.w3schools.com/sql/sql_insert_into_select.asp

You need a INSERT INTO SELECT statement

INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers;

Your specific case should be something like:

INSERT into wp_top_voted ('post_id','meta_value','todays_date' ) SELECT 'post_id' ,'meta_value' ,CURDATE()
FROM  'wp_postmeta' WHERE  'meta_key' =  'votes' ORDER BY 'meta_value' DESC   
LIMIT 10

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.