I'm working on an application that is deployed to Heroku and using the JawsDB add on to replicate my local MySQL database. I recently updated a table in the local MySQL database (Plans) to include two new rows, 'plan_dates' and 'plan_times', but the hosted JawsDB did not automatically sync with the changes made on my local connection.
I opened up the JawsDB database on MySQL using the connection string provided by Heroku to try and add in the rows manually. These are the rows in the Plan table that I am trying to edit:
database rows
I've searched online, but I cannot find any resources on how to add new (empty) rows to a table on MySQL -- all I can find online are references to 'INSERT INTO', which inserts specific values into rows, but that's not exactly what I'm looking to do. I did try running INSERT INTO as follows:
INSERT INTO Plans (plan_dates, plan_times)
VALUES(NULL, NULL);
but then I ran into the following error:
Unknown column 'plan_dates' in 'field list'
Am I missing a very simple command or is there any other way to add new empty rows to a table that has already been created in MySQL?
First of all, The columns are not exist in your table and you must add it to the table using ALTER Table query.
Syntax would be
ALTER TABLE table
ADD [COLUMN] column_name column_definition [FIRST|AFTER existing_column];
So your query should be
ALTER TABLE Plans
ADD COLUMN plan_dates Date AFTER UserId,
ADD COLUMN plan_times TIME AFTER UserId;
And you can use INSERT statement to add new empty rows.
INSERT INTO Plans (id, start_date, end_date, maxMins, totalMins, UserId, plan_dates, plan_times) VALUES(1, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
Related
Is it possible to insert data into an existing table in postgres database using apache drill.something similar to
insert into Post_db.test_schema.customer_account_holder_test select customer_id,source_system_id,salutation,first_name,middle_name,last_name,legal_name,gender,identity_proof_name,identity_proof_value from hive.schema_name.customer_account_holder limit 10
In apache drill, Insert is not supported.
You can creates a new table and populates the new table with rows returned from a SELECT query. Use the CREATE TABLE AS (CTAS) statement in place of INSERT INTO. CREATE TABLE name AS query;
I have the following sql table:
id|email|fbid
When I perform the query
INSERT INTO users(email,fbid) VALUES('randomvalue','otherrandomvalue')
I want to get the id of the inserted row. To do so, I've tried to edit the query like this:
INSERT INTO users(email,fbid) VALUES('randomvalue','otherrandomvalue') OUTPUT Inserted.id
But I'm getting:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near 'OUTPUT Inserted.id' at line 1
What could be the problem?
Unfortunately (as far as I can tell) mysql does not support output as sql-server does.
You do have an option for what you're trying to accomplish in a single row insert (assuming auto_increment primary key):
SELECT LAST_INSERT_ID();
This unfortunately would not work in the case of a batch insert - though in your case you are not (at least not in your example), so this should be fine.
I'm going to use the process i describe below to handle the same situation with a private at home (non-enterprise) application that i wrote for personal use. I know this question is a year old right now but there doesn't seem to be an adequate answer for batch processing. I can't find an adequate answer. MySQL doesn't seem to have the facilities built into it to handle this type of thing.
I had concerns about the reliability of this solution, when put into a production environment where multiple different users/jobs could access the same procedure at the same time to do the insert. I believe I have resolved these concerns by adding the connection id to the #by variable assignment. Doing this makes it so that the by has a: the connection id for the session and b: the name of the program/job/procedure doing the insert. Combined with the date AND time of the insert, I believe these three values provide a very secure key to retrieve the correct set of inserted rows. If absolute certainty is required for this, you could possibly add a third column of a GUID type (or varchar) generate a GUID variable to insert into that, then use the GUID variable along with #by and #now as your key. I feel it's unnecessary for my purpose because the process I'm going to use it in is an event (job) script that runs on the server rather than in PHP. So I am not going to exemplify it unless someone asks for that.
WARNING
If you are doing this in PHP, consider using a GUID column in your process rather than the CreatedBy. It's important that you do that in PHP because your connection can be lost in between inserting the records and trying to retrive the IDS and your CreatedBy with the connection ID will be rendered useless. If you have a GUID that you create in PHP, however, you can loop until your connection succeeds or recover using the GUID that you saved off somewhere in a file. The need for this level of connection security is not necessary for my purposes so I will not be doing this.
The key to this solution is that CreatedBy is the connection id combined with the name of the job or procedure that is doing the insert and CreatedDate is a CURRENT_TIMESTAMP that is held inside a variable that is used through the below code. Let's say you have a table named "TestTable". It has the following structure:
Test "Insert Into" table
CREATE TABLE TestTable (
TestTableID INT NOT NULL AUTO_INCREMENT
, Name VARCHAR(100) NOT NULL
, CreatedBy VARCHAR(50) NOT NULL
, CreatedDate DATETIME NOT NULL
, PRIMARY KEY (TestTableID)
);
Temp table to store inserted ids
This temporary table will hold the primary key ids of the rows inserted into TestTable. It has a simple structure of just one field that is both the primary key of the temp table and the primary key of the inserted table (TestTable)
DROP TEMPORARY TABLE IF EXISTS tTestTablesInserted;
CREATE TEMPORARY TABLE tTestTablesInserted(
TestTableID INT NOT NULL
, PRIMARY KEY (TestTableID)
);
Variables
This is important. You need to store the CreatedBy and CreatedDate in a variable. CreatedBy is stored for consistency/coding practices, CreatedDate is very important because you are going to use this as a key to retrieve the inserted rows.
An example of what #by will look like: CONID(576) BuildTestTableData
Note that it's important to encapsulate the connection id with something that indicates what it is since it's being used as a "composite" with other information in one field
An example of what #now will look like: '2016-03-11 09:51:10'
Note that it's important to encapsulate #by with a LEFT(50) to avoid tripping a truncation error upon insert into the CreatedBy VARCHAR(50) column. I know this happens in sql server, not so sure about mysql. If mysql does not throw an exception when truncating data, a silent error could persist where you insert a truncated value into the field and then matches for the retrieval fail because you're trying to match a non-truncated version of the string to a truncated version of the string. If mysql doesn't truncate upon insert (i.e. it does not enforce type value restrictions) then this is not a real concern. I do it out of standard practice from my sql server experience.
SET #by = LEFT(CONCAT('CONID(', CONNECTION_ID(), ') BuildTestTableData'), 50);
SET #now = CURRENT_TIMESTAMP;
Insert into TestTable
Do your insert into test table, specifying a CreatedBy and CreatedDate of #by and #now
INSERT INTO TestTable (
Name
, CreatedBy
, CreatedDate
)
SELECT Name
, #by
, #now
FROM SomeDataSource
WHERE BusinessRulesMatch = 1
;
Retrieve inserted ids
Now, use #by and #now to retrieve the ids of the inserted rows in test table
INSERT INTO tTestTablesInserted (TestTableID)
SELECT TestTableID
FROM TestTable
WHERE CreatedBy = #by
AND CreatedDate = #now
;
Do whatever with retreived information
/*DO SOME STUFF HERE*/
SELECT *
FROM tTestTablesInserted tti
JOIN TestTable tt
ON tt.TestTableID = tti.TestTableID
;
if You are using php then it is better to use following code :
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
where $conn is connection variable.
I'm seeing a weird behavior when I INSERT some data into a table and then run a SELECT query on the same table. This table has an auto-increment primary key (uid), and this problem occurs when I try to then select results where 'uid IS NULL'.
I've golfed this down to the following SQL commands:
DROP TABLE IF EXISTS test_users;
CREATE TABLE test_users (uid INTEGER PRIMARY KEY AUTO_INCREMENT, name varchar(20) NOT NULL);
INSERT INTO test_users(name) values('foo');
SELECT uid FROM test_users WHERE uid IS NULL;
SELECT uid FROM test_users WHERE uid IS NULL; -- no output from this query
I'd expect SELECT uid FROM test_users WHERE uid IS NULL to never return anything, but it does, sometimes. Here's what I've found:
Version of MySQL/MariaDB seems to matter. The machine having this problem is running MySQL 5.1.73 (CentOS 6.5, both 32-bit and 64-bit). My other machine running 5.5.37-MariaDB (Fedora 19, 64-bit). Both running default configs, aside from being configured to use MyISAM tables.
Only the first SELECT query after the INSERT is affected.
If I specify a value for uid rather than let it auto-increment, then it's fine.
If I disconnect and reconnect between the INSERT and SELECT, then I get the expected no results. This is easiest to see in something like Perl where I manage the connection object. I have a test script demonstrating this at https://gist.github.com/avuserow/1c20cc03c007eda43c82
This behavior is by design.
It's evidently equivalent to SELECT * FROM t1 WHERE id = LAST_INSERT_ID(); which would also work only from the connection where you just did the insert, exactly as you described.
It's apparently a workaround that you can use in some environments that make it difficult to fetch the last inserted (by your connection) row's auto-increment value in a more conventional way.
To be precise, it's actually the auto_increment value assigned to the first row inserted by your connection's last insert statement. That's the same thing when you only inserted one row, but it's not the same thing when you insert multiple rows with a single insert statement.
http://dev.mysql.com/doc/connector-odbc/en/connector-odbc-usagenotes-functionality-last-insert-id.html
In sql server and mysql
I want a query to identify the tables name which are affected using INSERT or UPDATE
Additional info:
1. I have more than two tables and all tables may not have indexes.
2. If a stored procedure execute I don't know what are the tables inserted or updated. But here I want to know.
Thanks.
You can do this in SQL server
SELECT TOP 1 *
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'AdventureWorks')
AND OBJECT_ID in (select OBJECT_ID(name) from sys.tables)
ORDER BY last_user_update DESC
not sure about MYSQL
taken from here and here
I run this query
CREATE TEMPORARY TABLE usercount SELECT * FROM users
I get this message
Your SQL query has been executed successfully ( Query took 0.1471 sec )
But when I try to access the newly created table using
SELECT * FROM usercount
I get this error
#1146 - Table 'abc_site.usercount' doesn't exist
Not sure why, I need to mention that I've did a good share of googling beforehand.
My version of PHPMyAdmin is 3.5.2.2 and MySQL 5.5.27
PHPMyAdmin (or rather PHP) closes the database connection after each screen. Thus your temporary tables disappear.
You can put multiple SQL statements in the SQL query box in PHPMyAdmin; this should be executed as one block and thus the temporary table is not deleted.
Temporary tables are temparar and after use thay Delete.
for example ,when insert data into database , first we can insert into temp table and thus when complete transaction , then insert into main table.
EXAMPLE :
//------------------------------------------
CREATE TEMPORARY TABLE TEMP
(
USERNAME VARCHAR(50) NOT NULL,
PASSWORD VARCHAR(50) NOT NULL,
EMAIL varchar(100),
TYPE_USER INT
);
INSERT INTO TEMP VALUES('A','A','A','1');
SELECT * FROM TEMP
//-----------------------------------------
Show A,A,A,1