MySQL INSERT … SELECT multiple rows

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



MySQL INSERT … SELECT multiple rows



I've been searching the MySQL documentation, Google and Stackoverflow, but I couldn't find the solution which suits my needs.



I have 2 tables:
Contract: contract_id, contract_client_id, contract_property_id, contract_tenant_id, contract_startdate, contract_enddate, contract_price



Ledger: ledger_id, ledger_trans_date, ledger_period, ledger_property_id, ledger_tenant_id, ledger_value



I want to populate the ledger with some columns from the contract table and used the following statement:


INSERT INTO ledger (ledger_trans_date, ledger_period, ledger_property_id,
ledger_tenant_id, ledger_value)
VALUES ('01-08-2018', '01-08-2018', (SELECT contract_property_id,
contract_tenant_id, contract_price FROM contract));



But I get the following error: Error Code: 1136. Column count doesn't match value count at row 1.



I tried this one as well:


INSERT INTO ledger (ledger_trans_date, ledger_period, ledger_property_id,
ledger_tenant_id, ledger_value)
VALUES ('01-08-2018', '01-08-2018',
(SELECT contract_property_id FROM contract),
(SELECT contract_tenant_id FROM contract),
(SELECT contract_price FROM contract));



But than I get the following error: Error Code: 1242. Subquery returns more than 1 row.



I hope someone can help me ahead and tell me where I went wrong...
In case you need more info, please don't hesitate to ask.



Thanks a lot in advance.




1 Answer
1



Do it like this:


INSERT INTO ledger (ledger_trans_date, ledger_period, ledger_property_id,
ledger_tenant_id, ledger_value)
SELECT '2018-08-01', '2018-08-01', contract_property_id,
contract_tenant_id, contract_price FROM contract;





This gives a syntax error: Error Code 1064. If I understood the documentation correct this is due to the fact of VALUES (SELECT '01-08-2018', '01-08-2018' ... as the dates are a string... Correct me if I misunderstood.
– Dennis
Aug 10 at 22:35






Wrong date format, it should be 'YYYY-MM-DD' . Rest is fine.
– Sookie Singh
Aug 10 at 22:43






That doesn't solve the syntax error. I did it according to the code above you sent and change it to 2018-08-01.
– Dennis
Aug 10 at 22:45





Then please check if ledger_trans_date and ledger_period are in date/datetime format or not?
– Sookie Singh
Aug 10 at 22:46


ledger_trans_date


ledger_period





@Dennis Did you checked?
– Sookie Singh
Aug 10 at 22:51






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard