I have a table, table_a, in my MySQL db. (I am using PHP for scripting)
Now I have created another table, after realizing its necessity, called table_b. For every row in table_a I want to insert some of its values into table_b, and then affix a timestamp (DATETIME type).
This is where I am:
$query = "INSERT INTO table_b('id_a', 'type_a', 'date_a') SELECT table_a.id, table_a.type, '$datetime'";
where $datetime is a time value (php).
I'm not sure this is going to work. Could someone tell me a correct way to do this.
(Aside: I am aware I'm not using prepared statements - that's for another day)
Thanks in advance.
With thanks to all the comments, the answer is simple:
$query = "INSERT INTO table_b(id_a, type_a, date_a) SELECT table_a.id, table_a.type, '$datetime' FROM table_a";
This adds the desired values from every row of table_a into table_b.
Related
I hope I have got the title right as I don't really know how to word this!!
Here's the background...
I have a app inserting data to a db. The db holds a date field and data field (there are others but for simplicity these two are the only ones needed). There can only be 8 entries on the same date, no more. In normal operation this is not really an issue but twice a month the database gets hit hard towards the end of the day.
The way I currently do it, is to query how many records there are for a date. If that's less than 9 I insert the data.
It has never happened yet but my concern is that request A comes in and checks the DB and finds there are 7 records. OK to insert. But before A can insert, request B comes in and finds only 7 records. OK to insert. But that would then enter 9 records on one date. This can't happen.
I think there are two solutions to this but would like to know A, if I'm right at all! or B is there a better solution.
I think...
A) I could do it in a transaction. However, would I still no encounter the same problem? As far as I am aware as long as no queries in a transaction fail then it runs anyway.
or
B) Use a stored procedure to check first then insert. I have had very little experience with stored procedures so I must admit I have no idea what I'm talking about here!
Alternatively, is there a way to get a single query to check first if there is less than 9 entries??
Many Thanks in advance,
Gavin
You are afraid of that someone would insert a new record before other one insert it even in the million second?
I have this question too, so I just searched something for you, you can do this with two ways:
For example if you have a table which named date_table and it looks like:
date_field
----------
1998-07-13
1992-03-23
1998-09-17
1994-02-30
A) Count the rows, then insert it when it's under 8 rows. (Using PHP and MySQL)
First, get how many rows are there by this:
SELECT COUNT(*) AS Num FROM date_table WHERE date_field = '1998-07-13'
so you'll get a Num field which told you how many rows were 1998-07-13,
then using PHP to prevent user insert the same date when it's equal 8 by:
<?php if($DB['Num'] >= 8) exit('Sorry, no more same value'); ?>
otherwise insert the row.
Or you don't trust PHP, or you think someone would insert the row more earlier than 1 million second
B) Insert it when it's only under 8 rows were same with only one query:
INSERT INTO date_table (date_field)
SELECT '1998-07-13'
FROM dual
WHERE (SELECT COUNT(*) FROM date_table WHERE date_field = '1998-07-13') < 9;
BEWARE: dual is a mysql system table, so you don't need to create it
If you don't understand how the above query works:
insert into TABLE_NAME (TABLE_FIELD)
select VALUE_YOU_WANT_TO_INSERT
from dual
where (select count(*)
from TABLE_NAME
where THE_FIELD_YOU_WANT_TO_CHECK = '1998-07-13'
) < LESS_THEN_HOW_MUCH;
EDIT: add more fields change the following lines:
INSERT INTO date_table (field1, field2, field3)
SELECT value1, value2, value3
I want to insert data partially from select statement..
For example..
I have one table named movie..here's the fields :
-id_movie
-tittle
-studio
-time
And another table named reservation.. here's the fields :
-id_reservation
-tittle
-studio
-time
-seat_1
-seat_2
So, I want to insert value of tittle, studio, and time into reservation table that getting from select statement from movie table. But I'm a little bit confuse about another field in reservation table (id_reservation, seat_1, seat_2).. They're actually don't exist in the first table (movie table)
so how to write the query?
any simple example would be very helpful
thank you
$query = "INSERT INTO reservation(tittle,studio,time)
SELECT tittle,studio,time FROM movie";
INSERT INTO reservation (
tittle,
studio,
time
)
SELECT tittle,
studio,
time
FROM movie;
But you better not have NOT NULL on the columns you leaving without values.
If you want mysql query then:
"INSERT INTO reservation(tittle,studio,time)
SELECT tittle,studio,time from movie";
First do a SELECT from "movie" to obtain the fields you need from that table.
You will have the fields you need stored in 3 variables, say $title, $studio, $time.
As per the table reservation, the field id_reservation should be the PK so set it to autoincrement. You don't have to insert that value as it does it automatically in every insert.
The fields seat_1 and seat_2 will depend on other facts than the data you get from the first table. You should obtain the free seats (I guess there is another table with the total amount of seats), and select 2 using some kind of logic (for example, that they are next to each other)
So in the end, the INSERT query for the table reservation should look like
"INSERT INTO reservation (title, studio, time, seat_1, seat_2) VALUES('$title', '$studio', '$time', $seat_1, $seat_2)");
what am doing is clonning an old database to new one with different structure but should have same old data
is it possible to do an insert into insert that return id of the insert query
INSERT INTO tab1 (nom,id_2) VALUES
("jack",(INSERT INTO tab2 (pass) VALUES ("1234")));
in INSERT INTO tab2 (pass) VALUES ("1234") i want to get the id of the insert
but no luck!! (i want it in one sql query (i already know about mysql_insert_id) )
thanks in advance
You cant do this on a single query - use mysql_insert_id() to get the last inserted id for example :
mysql_query('INSERT INTO tab2 (pass) VALUES ("1234")');
$lastid = mysql_insert_id();
mysql_query('INSERT INTO tab1 (nom,id_2) VALUES ("jack",'.$lastid.')');
insert id can be retrieved in mysql as well, so here is a version with no PHP involved (it however performs 2 queries)
INSERT INTO tab2 (pass) VALUES ("1234");
INSERT INTO tab1 (nom,id_2) VALUES("jack",LAST_INSERT_ID());
Lock the table, insert, select max(id), unlock table. This is the only way outside creating your own sequence tables like in postgres if you are adverse for some reason to the last insert id functions. This approach however is going to be like pouring tar into a blender if your table is moderate to high writes.
You can't do this as a single insert because inserts are atomic that is, the ID isn't determined until the statement completes.
Wrap both statements in a transaction and you will get your ID, and atomicity.
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
I need to get the ID (a column) from the last row inserted, in a table. I'm wondering if there's any way to somehow embed that in another query, to avoid having two different querys? It seems much simpler, and i believe i've seen it somewhere before.
Something like this:
$query = "INSERT INTO a_table (x, y) VALUES ((SELECT id FROM another_table ORDER BY id DESC), 'y...')";
Any ideas how to do that?
Thanks.
If you're looking to get the newest record created by your script, you should never do it this way in the first place. What if another instance of your script created a record at the same time?
mySQL's LAST_INSERT_ID() will return the last ID created over this specific connection. However, you must call it immediately after your insert statement.
If getting the highest ID is literally what you want, GSto's answer will work for you.
INSERT INTO a_table (x, y) VALUES (SELECT max(id), 'y...' FROM another_table);
Yes, MySQL has an INSERT .. SELECT statement:
example:
INSERT INTO a_table (x,y) SELECT id,'y' FROM another_table ORDER BY id DESC
although keep in mind, unless you have an auto_incrementing ID field, the order by clause is pointless here.