I'm quite confused with sql INSERT INTO. Do I need to put JOIN? or INNER JOIN when I'm going to put into different table?
$sqlinsert = "INSERT INTO forum_topic (topic_title, topic_message, thread_id)
VALUES
('$topic','$message','$thread_id')";
I know this code is works for only one table but not for two. However, what I want is $message into post_message in other table.
In forum_topic table, there is post_id, post_message, date, and topic_id.
But there is forum_post table where I want to put $message into post_message in forum_post.
So, in forum_post table, there is post_id, post_message, date, and topic_id.
So do I need to JOIN or INNER JOIN? I don't know which one I should code them.
PS : I know the question is quite hard for you to understand. How I wish i can put image but I don't have 10 reputations, so i decided to do like this.
You cannot insert into multiple tables with one query, but you can use transactions to make sure that the operation is atomic.
BEGIN;
Your queries here
COMMIT;
When you need to execute several interdepending queries, some of them might result in error. So to keep the database consistent you would like to execute them as all-or-none (You can read about ACID).
MySQL also supports transactions but only with some of its storage engines (e.g. InnoDB, but not MyISAM).
The pseudo-code of usage looks like this.
start transaction
try {
execute query 1
execute query 2
...
commit transaction
catch {
rollback transaction
}
If you are using PDO, look at these functions.
In case of mysql_query, you can use
mysql_query("START TRANSACTION");
mysql_query("COMMIT");
mysql_query("ROLLBACK");
You don't use joins. You use separate queries for each table.
insert into table1
(field1, field2, etc)
values
(value1, value2, etc);
insert into table2
(field1, field2, etc)
values
(value1, value2, etc);
To insert into multiple tables you must use multiple queries.
Example:
$sqlinsert1 = "INSERT INTO forum_topic1 (topic_title1, topic_message1, thread_id1)
VALUES
('$topic1','$message1','$thread_id1')";
$sqlinsert2 = "INSERT INTO forum_topic2 (topic_title2, topic_message2, thread_id2)
VALUES
('$topic2','$message2','$thread_id2')";
Join are used for Selecting queries.
Example for a Join:
$sqlselect = "SELECT * FROM forum_topic
Join table2 on thread_id = table2id
WHERE topic_title = $topic";
Related
I want to copy columns from one table to another which is not the problem when I want to copy "AllInOne".
I will write:
INSERT INTO table2 SELECT * FROM table1 WHERE condition;
If I need to copy only part of the columns I will write:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ... FROM table1 WHERE condition;
BUT
What if I need to copy all columns, but I need two or three columns with specified PHP variables that I am getting from $_POST[] or $_GET[]?
If I will have in the table only maybe ten columns together I will write it "manually" which is my second example. But I have more than 30 columns in my tables....
Therefore I am trying to find some combination where I can INSERT * and also specify column2, column3 for example.
Is there some way how to do that? Something like this:
NSERT INTO table2 ( *, Price, Customer) SELECT ( *, '451', 'John')
FROM table1 WHERE condition;
Therefore I am trying to find some combination where I can INSERT * and also specify column2, column3 for example
This is really more of a SQL question then, if I'm not mistaking something? If your question is about binding variables in PHP then that's a different story, but it seems from your question that you know how to do that already.
SQL doesn't support a syntax that's like, "* for all the columns except for these columns." You'll just have to list out every column in the query. Using INSERT INTO ... SELECT * won't work for what you want to do, and is considered bad practice anyway (for example, if you drop or add a column from the table later, the query to select one into the other will break).
If I will have in the table only maybe ten columns together I will write it "manually" which is my second example. But I have more than 30 columns in my tables...
Is that really so bad though? It's a small investment for code that works :)
You are close. Just don't use the parentheses:
INSERT INTO table2 (column1, column2, . . ., price, customer) -- list all columns here
SELECT t1.*, -- I advise you to list the columns here too
451, 'John'
FROM table1 t1
WHERE condition;
I know this is possible using transaction but I want to do it using single mysql query.
this is which common format transaction
START TRANSACTION;
SELECT #A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=#A WHERE type=1;
COMMIT;
but I need to know a single mysql query is possible?
Normally, you can not do this in MySQL. But you can do this using concat query.
INSERT INTO your_table
(value1,value2,value3)
VALUES
(a,b,c),
(d,e,f),
(i,j,k);
But this is not your question answer. so Your question answer is NO. MYSQL is not support it still now.
No, it can't be done in single statement like
insert into table1,table2
either you do separately like
insert into table1 ...
insert into table2 ...
(OR)
Wrap the insert statements in stored procedure and call that procedure like
create procedure sp_insert_multiple
as
begin
insert into table1 ...
insert into table2 ...
end
Call the SP
exec sp_insert_multiple
You can't do this. However, you can use a transaction and have both of them be contained within one transaction.
START TRANSACTION;
INSERT INTO table_1 VALUES ('1','2','3');
INSERT INTO table_2 VALUES ('one','two','three');
COMMIT;
See the following rule
Normally it is not possible to insert multiple table in single query. you can insert multiple row in a single table . like as
INSERT INTO tbl_test
(a1,a2,a3)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
you can do this in Oracle
by using procedure you can insert
create procedure insert_query
as
begin
insert into tbl_test1(a1,a2,a3) VALUES (1,2,3)
insert into tbl_test2 (b1,b2,b3) VALUES (1,2,3)
end
you can do that like coz
MySQL doesn't support multi-table insertion in a single INSERT statement.
INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)
here is a link of detail answer..
sql - insert into multiple tables in one query
I am trying to write a dual MySQL query which archives the content of a table to another table, then deletes the original row in the original table.
I have the base query working just fine in other areas. The query below relies on a second table to help select which rows need to be archived & deleted.
I am getting a syntax error where the AS appears in the nested select of the first query and near the AS in the delete query.
I have researched and researched and tried a bunch of different code combos, but I can't get the queries working. The queries are written in PHP using PDO, so please ignore the PDO tags, they are not the problem.
INSERT INTO usetwca (r_id, c_id, o_id, t_id, s_id, ip_address, timestamp, timestamp_archived) SELECT :r_id, usetwc.c_id, usetwc.o_id, usetwc.t_id, usetwc.s_id, usetwc.ip_address, usetwc.timestamp, :timestamp FROM usetwc JOIN useo ON useo.o_id = usetwc.o_id AND useo.best_fit IS NULL WHERE usetwc.user_id = :user_id;
DELETE FROM usetwc JOIN useo ON useo.o_id = usetwc.o_id AND useo.best_fit IS NULL WHERE usetwc.user_id = :user_id;
You should implement this as a BEFORE DELETE trigger on the `users_sessions_exercise_t_ws_correlation' table.
Have a look at this answer as a good example.
Here's a good general reference on using Triggers for Logging.
I was able to get my queries working.
INSERT INTO usetwca (r_id, c_id, o_id, t_id, s_id, ip_address, timestamp, timestamp_archived) SELECT :r_id, usetwc.c_id, usetwc.o_id, usetwc.t_id, usetwc.s_id, usetwc.ip_address, usetwc.timestamp, :timestamp FROM usetwc JOIN useo ON useo.o_id = usetwc.o_id AND useo.best_fit IS NULL WHERE usetwc.user_id = :user_id;
DELETE usetwc FROM usetwc INNER JOIN useo ON useo.o_id = usetwc.o_id AND useo.best_fit IS NULL WHERE usetwc.user_id = :user_id
I have two SQL queries:
$res1 = mysql_query("SELECT * FROM `table1` WHERE `user`='user'");
$i = mysql_fetch_assoc($res1);
$value1 = $i['num'];
And:
$res2 = mysql_query("INSERT INTO `table2` (`name`,`num`) VALUE ('name','$value1')");
How to combine the two SQL queries into one? I need to get the value of the variable from of a second query for the first request. Is it possible?
This query with a subquery should do the trick nicely for you:
insert into table 2 (`name`, `num`)
values ('name', (select `num` from table1 where `user`='user'));
This assumes that you aren't using anything but the num from your second query as it doesn't seem to be used in your original code.
Edit: Also, I see that this is an insert, not just a select statement, but you might well benefit from reading a rather lengthy question and answer I put up which covers off multiple tables and SQL covering unions, joins, subqueries and a bunch more stuff.
Can you use the INSERT INTO ... SELECT ... syntax?
E.g. something like:
INSERT INTO table2 (name, num)
SELECT 'name', num
FROM table1
WHERE user='user'
(untested so please forgive any minor errors here...)
Scrap this.
The best answer is to have PHP have the data that MYSQL is going to need. Doing it any other way will cause bottlenecks and is inefficient.
I have two tables. One table is meant to serve as a transaction history and the other is a log of member details. When a report is run, I want to move pieces of the member details into the transaction history but ALSO update some field records which would not otherwise exist.
Is it possible to select all records which meet a specific criteria, insert only pieces of the matching row into another table AND update other fields in a single query?
For example:
In table 2, i have member name, date registered, and memberid. I want to move the above records into table 1 but also update the field (status) equal to 'processed'.
Note: I am also using php and pdo to connect to a mysql database.
Is this possible within a single query?
You didn't specify whether the rows you want to update are the same as the ones you are inserting. I am assuming they are:
insert into table1
(member_name, date_registered, memberid, status)
select member_name, date_registered, memberid, 'processed'
from table2
where SomeField = MyCriteria
After much consideration - I decided to use ircmaxell's advice and simply run multiple queries. It ends up not only making things easier but allows me to customize my sorting much easier.
As he said above, "Don't get caught in the trap of less is always better"
Yes:
SELECT *, "processed" INTO table2 FROM table1
You will have to adapt based on the table structures, perhaps even write out all the fields:
SELECT field1, field2, field3, "processed" INTO table2 FROM table1
Of note, this assumes you want to write into table 2 including the processed variable (Might I suggest a boolean?) if you want the "Processed" in the other table it will get more complicated.
Edit: Apparently mysql doesn't support select into so...
INSERT INTO table2 SELECT field1, field2, field3, "processed" FROM table1
Redfilters code works