MySQL - insert into statement requires me to enter primary key - mysql

I'm pretty much a complete newbie to SQL, I'm using MySQL with SQLyog. I have five fields, StudentForename, StudentSurname, StudentAge, StudentHouse and StudentID for the Primary Key. The StudentID field is set as a Primary Key and Not Null and AutoIncrement. I'm trying to use an INSERT INTO statement without having to entering the primary key - apparently I shouldn't need to, it should update itself. But it's not working, it's returning the error "Column count doesn't match value count at row 1". Here's the code I'm using. I've already set up the table, so I haven't got the code for the query that
INSERT INTO students VALUES('Harry', 'Potter', 'Slytherin', 30)

You will need to explicitly state which columns you will provide values for, otherwise it is assumed you will provide values for all columns. E.g.
INSERT INTO students (`first_name`, `last_name`, `house`, `age`) VALUES('Harry', 'Potter', 'Slytherin', 30)
(I made up column names, swap these with your columns)

Related

SQL "Replace Into" drop some of my rows

I'm trying to write a SQL statement that replace instead of update.
The columns of my table look like that
(id
block
region
login
password
email
business
firstname
name
version
updatable
bodyshop_id
mac
register_date
lastvisite_date
enum_test
address1)
and when I run a statement like this:
REPLACE INTO `users` (`login`, `firstname`, `region`, `address1`, `enum_test`, `block`, `id`) VALUES ('Samira GO', 'Samira', 'all', 'lmklm', '1', '0', '2')
Samira have the id number two. (target of the replace ;) )
The person with the id number one is drop by the request.
(The primary id key of the table is id+login+email)
(When I ask this request to SQL it told me that 3 lines are affect)
If you want to ask, id, login, or email are some primary value, so I don't understand how it would be able to change some value with another id or login
From the MySQL REPLACE doc:
The REPLACE statement returns a count to indicate the number of rows affected. This is the sum of the rows deleted and inserted. If the count is 1 for a single-row REPLACE, a row was inserted and no rows were deleted. If the count is greater than 1, one or more old rows were deleted before the new row was inserted. It is possible for a single row to replace more than one old row if the table contains multiple unique indexes and the new row duplicates values for different old rows in different unique indexes.
So, it sounds like one row was inserted and two rows were deleted.
Examine your table definition and see if there are any UNIQUE indexes other than the PRIMARY KEY. Note also that while you say the primary key is id, login, email, your query doesn't specify email. If two rows existed that matched id and login but had different email, they may have both been deleted.
You may also consider that what you wanted to do is an INSERT ... ON DUPLICATE KEY UPDATE instead of a REPLACE. REPLACE functions more like a combined DELETE then INSERT.

Why everytime I go and execute insert statements that I want to insert into a table, it says field doesn't have a default value?

Here is the screenshot of the Parts table
INSERT INTO Supplies(Cost)
VALUES(10.0);
INSERT INTO Supplies(Cost)
VALUES (20.0);
INSERT INTO Supplies(Cost)
VALUES (30.0);
SELECT * FROM supplies;
Here is the Supplier table
Hello Everyone,
I am working on creating a database (three tables) in MySQL and every time I run an insert statement to input a record into my Supplies table, it says 'Field Supplier_SupplierID' doesn't have a default value'. When I created my model in MySQL, I already auto-incremented 'Parts_PartID' column and that error doesn't exist anymore. So why is it doing it with 'Supplier_SupplierID' column now? Can someone please help me? Here is my model pic and sample of SQL code when I insert records into the Supplies table.
You cannot insert into Supplies without providing the foreign keys for the Parts table and Suppliers table. While those primary keys in those tables may be incrementing automatically, they need to be already known when inserting into Supplies.
Typically you will use the known PartID and SupplierID that have previously been created when inserting into the Supplies table. Those columns cannot be NULL (by definition of your table).
'Field Supplier_SupplierID' doesn't have a default value' means that you are not providing a value, there is no default value and it's not allowed to be NULL.

mysql - INSERT... ON DUPLICATE KEY UPDATE, but not really...?

Hi I've been trying to get this to work, I thought I had it with mysql - INSERT... ON DUPLICATE KEY UPDATE, but no luck.
I have a table as such:
sessionID is unique,
productID references another table and is not unique, but not common, should be a max of 3 rows containing the same value,
sessionType is either 1, 2 or 3, and would link with productID,
I need to check if the table has a row where there is a matching pair of productID and sessionType, if there is then sessionDate & sessionCapacity in that row should be UPDATED, if there isn't then a new row inserted.
$vals = array($pID,$data['pSessionDate'],'1',$data['pQty'],$pID,$data['pSessionDate'],'1',$data['pQty']);
$db->Execute("INSERT INTO VividStoreSessions (pID,sDate,sType,sCapacity) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE pID=?,sDate=?,sType=?,sCapacity=?",$vals);
Hope that makes sense to someone and thanks in advance for any help!
Your insert looks valid. But, first you need a unique index/constraint:
create unique index unq_VividStoreSessions_productId_sessionType
on VividStoreSessions, productId, sessionType)
Then you can write the code to only use four parameters:
INSERT INTO VividStoreSessions (pID, sDate, sType, sCapacity)
VALUES (? ,?, ?, ?)
ON DUPLICATE KEY UPDATE sDate = VALUES(sDate), Capacity = VALUES(Capacity);
Finally, you need to ensure that sType only takes on the values of 1, 2, or 3. Perhaps you want to enforce this at the application layer. Otherwise, you need a trigger or foreign key constraint to ensure that there are only three rows.

MySQL update if exists

I have been trying to do insert / update records in a mysql table. Cannot use ON DUPLICATE KEY because i have nothing to do with the primary key.
Basically i have to update a record in the database
INSERT INTO table (city, state, gender, value) VALUES ("delhi","delhi","M",22)
If a record of that city, state, gender exists, then simply overwrite the value.
Can i achieve this without sending two queries from the programming language
actually you can still use ON DUPLICATE KEY, just add a unique index on the following columns, eg
ALTER TABLE tbl_name ADD UNIQUE index_name (city, state, gender)
your query now will be,
INSERT INTO table (city, state, gender, value)
VALUES ('delhi','delhi','M', 22)
ON DUPLICATE KEY UPDATE value = 22
Keep in mind that constructs such as ON DUPLICATE KEY and REPLACE INTO were specifically designed to prevent exactly that. The only other way to prevent two queries from your application layer is by declaring a database function that does the same things.
Therefore, add either a UNIQUE(city, state, gender) key or a primary key that spans the same columns. The difference between the two lies in the value range of each column; primary keys force NOT NULL whereas UNIQUE allows for columns to be NULL.
The difference is subtle but can sometimes lead to unexpected results, because NULL values are considered to be unique. For example, let's say you have this data in your database:
nr | name
123 | NULL
If you try to insert another (123, NULL) it will not complain when you use UNIQUE(nr,name); this may seem like a bug, but it's not.

MySQL: Advanced insert if not exists

I have a table with with essentially three columns: user_id, setting, and value. I'm trying to use the following code:
INSERT INTO 'user_settings'(user_id, setting, value)
VALUES (1234, setting_1, 500)
ON DUPLICATE KEY UPDATE user_id = 1234, setting = setting_1'
This works great when creating a new setting, and it doen't generate duplicate records. The problem comes when I want to change the value- this won't work after the previous query has run:
INSERT INTO 'user_settings'(user_id, setting, value)
VALUES (1234, setting_1, 999)
ON DUPLICATE KEY UPDATE user_id = 1234, setting = setting_1'
No rows are affected. Clearly I'm missing something...
IMPORTANT: I am not able to alter the database (new primary keys or something).
UPDATE: It seems my understanding of ON DUPLICATE KEY is wrong. But the question remains- what is the most efficient way way to accomplish this?
Answered in a comment below: "If the Primary (or Unique) key is (user_id, setting), then use: ... ON DUPLICATE KEY UPDATE value=999".
Assuming you actually have a unique key on user_id, you are getting "no rows affected" because you aren't changing anything in the second query. I think what you want to do is update the value field as well:
INSERT INTO 'user_settings'(user_id, setting, value)
VALUES (1234, setting_1, 999)
ON DUPLICATE KEY UPDATE setting = setting_1,value=999
Without value in there, you're just setting the user_id and the setting field to the same values they were before, and MySQL doesn't need to update the record.
If you don't have a unique key on user_id, you'll have to find a different approach, as the ON DUPLICATE KEY UPDATE won't trigger.