MySQL: How to fetch data from two table and store into one table
I have three table.2 data comes from 2 table and insert it into another table. Let: tbl_id hold the field id and tbl_msg hold the field msg.
tbl_id tbl_msg
id msg
------ --------
12开发者_如何学JAVA34 test_msg
5678
9876
Now my desired output should be in tbl_info
id msg
--- -------
1234 test_msg
5678 test_msg
9876 test_msg
I write a query but its showing error that: Subquery returns more than 1 row. My query is below:
INSERT INTO tbl_info (id,msg) VALUES((SELECT id FROM tbl_id),(SELECT msg FROM tbl_msg))
You need to write a single SELECT statement which returns teh rows exactly as you want them inserted.
The 2 inner selects you have return all the id's from tbl_id and all the msg from tbl_msg, which doesn't make much sense.
First write the select, e.g.:
SELECT tbl_id.id, tbl_msg.msg
FROM tbl_id
JOIN tbl_msg ON tbl_id.fk = tbl_msg.fk
WHERE (...)
Then use it for the INSERT:
INSERT INTO tbl_info (id, msg)
SELECT tbl_id.id, tbl_msg.msg
FROM tbl_id
JOIN tbl_msg ON tbl_id.fk = tbl_msg.fk
WHERE (...)
UPDATE according to OP's comments:
INSERT INTO tbl_info (id, msg)
SELECT tbl_id.id, single_msg.msg
FROM tbl_id
JOIN (SELECT msg
FROM tbl_msg
WHERE CURDATE()=DATE_FORMAT(date_time,'%Y-%m-%d')
ORDER BY date_time DESC LIMIT 1) as single_msg ON 1=1;
This will not be very efficient because the inner select will be executed for each record in tbl_id. A more efficient solution may be:
SELECT msg INTO @msg
FROM tbl_msg
WHERE CURDATE()=DATE_FORMAT(date_time,'%Y-%m-%d')
ORDER BY date_time DESC LIMIT 1;
INSERT INTO tbl_info (id, msg)
SELECT tbl_id.id, @msg
FROM tbl_id;
精彩评论