there is a table customers with three columns (Id, name, Phone).
For example there is charachter with id 1 and name is Tom, and there are a lot of differents id and names so i need to add a phone number solely for tom in this sutiation, how can i do it?
i tried this:
INSERT INTO Customers (Phone) values ('a Number') WHERE Id = 1;
I can get that i use condition "where" wrong, how should i use it right in my situation, please help, and thanks.
It seems that you actually want an update here:
UPDATE Customers
SET Phone = 'a Number'
WHERE Id = 1;
If you really do want to add a new record, then drop the WHERE clause:
INSERT INTO Customers (Phone) VALUES ('a Number');
If the Id column be auto increment, then MySQL will auto generate a value for the Id.
In the described case (update of already existing record) you should use UPDATE statement instead of INSERT:
UPDATE Customers SET Phone = "customer_phone_number_here" WHERE Id = 1;
Hope, this link would be useful as well.
Related
I want to add the values to the columns where name=Michael for example it seems there is no way to do that
I think you want to ask that you want to update values in columns of a table in which name = Michael.
For that :
update tablename
set col1='val1', col2='val2', col3='val3'
where name = 'Michael'
I have a following map table, with a unique key on the name column:
id | name
1 aaa
2 bbb
3 ccc
I want to get a newly created ID if I insert a new value to this table, like this:
INSERT IGNORE INTO map VALUES(null, 'ddd');
I know I can do this with getLastId() function. But I also want to get ID if a name already exists, and getLastId() function returns 0 in such case:
INSERT IGNORE INTO map VALUES(null, 'ccc');
Is this possible to do with one SQL, and without checking if a record exists, etc?
I think you need to go the extra mile for that one:
check if exists - when so: get ID of that name
if not: SELECT LAST_INSERT_ID();
Depends on what qualifies as a single query.
When you make use of INSERT INTO ... ON DUPLICATE KEY UPDATE you can control the LAST_INSERT_ID() in such a manner that it will return the new id on insert and the id of the row "updated" on update:
INSERT INTO map (name) VALUE ('ccc')
ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id);
That will make the LAST_INSERT_ID() then return the map.id of the row you're interested in.
Whatever the API is that you name as the getLastId() (I don't know it so I can't provide more pointers on it) this may not work and you would then need to fire a second query to obtain it:
SELECT LAST_INSERT_ID();
See as well:
MySQL ON DUPLICATE KEY - last insert id? (Stackoverflow Q&A, Apr 2009)
What I am trying to do is something like this
INSERT INTO BOOKS(borrower_name,isbn) VALUES("Jane",SELECT isbn from TABLE...);
This is wrong obviously. But I am trying to get something that would work the way this would (if it did).
You were very close
INSERT INTO books (borrower_name, isbn)
SELECT 'Jane', isbn
FROM table_name
-- WHERE id = ?
You might want to limit number of rows coming from table_name by using WHERE clause and proper condition(s)
Here is SQLFiddle demo
More over if you meant to return from SELECT only a scalar value (just one ISBN) then you were correct in the first place and could've used syntax showed in your question
INSERT INTO books (borrower_name,isbn)
VALUES ('Jane',
(
SELECT isbn
FROM table_name
WHERE id = 1
));
Here is SQLFiddle demo
What you were doing is also right, u only missed () for select statement:
INSERT INTO BOOKS(borrower_name,isbn) VALUES("Jane",SELECT isbn from TABLE...);
should be modified to:
INSERT INTO BOOKS(borrower_name,isbn) VALUES("Jane",(SELECT isbn from TABLE...));
and it will work perfectly fine!! here is the SQLFiddle demo
INSERT INTO BOOKS(borrower_name,isbn)
SELECT 'Jane', isbn from TABLE
Check This My Answer...
Example:
I have two table Employee and Client
Insert into Employee (name, city) values((select name from client where id=2),'example');
follow this method
I have a table that looks like this:
Number | Name
--------+--------
123 | Robert
This is what I want to do:
If the Number is already in the database, don't insert a new record.
If the Number is not in the databse, but the name is, create a new name and insert it. So for example, if I have a record that contains 123 for Number and Bob for Name, I don't want to insert it, but if I get a record that contains 456 for Number and Robert for name, I would insert 456 and Robert1. I was going to check for duplicates individually like:
SELECT * FROM Person where Number = 123;
//If number is not found
SELECT * FROM Person where Name = 'Robert';
//If name is found, add a number to it.
Is there a way I can combine the two statements?
There are actually two problems in your question. The first problem is to make Number column unique and the second one is to increment the column Name by appending a number if it already exists.
FIRST PART
Since the number is UNIQUE, enforce a UNIQUE constraint on the column. It could be a PRIMARY KEY or a UNIQUE KEY.
If the column has no KEY and you want to make it PRIMARY, here is the ALTER statement:
ALTER TABLE TableName ADD CONSTRAINT tb_pk PRIMARY KEY (Number)
SQLFiddle Demo
but if you only want it to be UNIQUE and not a primary key,
ALTER TABLE TableName ADD CONSTRAINT tb_uq UNIQUE (Number)
SQLFiddle Demo
SECOND PART
You can actually do it without using join.
INSERT INTO TableName(Number, Name)
SELECT 124 AS Number,
CONCAT('Robert', COALESCE(MAX(CAST(REPLACE(Name, 'Robert', '0') AS UNSIGNED)) + 1,'')) AS Name
FROM TableName
WHERE Name LIKE 'Robert%'
SQLFiddle Demo
SQLFiddle Demo (added more example)
SQLFiddle Demo (throws exception due to uniqueness)
Some details:
when the value supplied on column Number already exists, it will throw an error since the column is unique. I have read a comment from a deleted posts saying: "..Number is not unique, but if it does exist, I don't want to enter a record." -- it does not make any sense if you don't want to add uniqueness on the column. How will you know if the number already exists or not? Doing a little check for the existence of Number feels like a little overhead for me. So my best recommendation is to enforce uniqueness.
SELECT * FROM Person WHERE Number = 123 OR Name = 'Robert'
I haven't worked with SQL for some time, so this may be wrong ;)
Edit:
$number = 123;
$name = 'Robert';
$query = mysql_query("SELECT * FROM Person WHERE Number = $number OR Name = '$name' ");
if (mysql_num_rows($query) == 0 ) {
//-> Add your record, it's unused
} else if (mysql_result($query, 0, 'number') == $number && mysql_result($query, 0, 'name' == $name)) {
//combination of number and name already exists -> modify name and add record
} else {
echo "Number is used by another name";
}
Use this query, for insert the row [123, 'Robert']. if you want insert other values, change 123 & Robert values in below query:
insert into Person (Number,Name)
select 123, IF(mn.MaxNumber is NULL,'Robert',concat('Robert',mn.MaxNumber+1))
from (SELECT 'foo') foo
left JOIN (select max(CONVERT(SUBSTR(Name,LENGTH('Robert')+1),UNSIGNED)) `MaxNumber`
from person where name rlike '^Robert[0-9]*$') mn on 1=1
where Not Exists (select * from Person where Number=123)
NOTE: if Robert exists in the table, above query inserts Robert1. if Robert1 exists, it inserts Robert2, and so on .
make both number and name unique.
ALTER TABLE `person` ADD UNIQUE (`number` ,`name`);
You can now do a insert with ON DUPLICATE
INSERT INTO `person` (`number`, `name`, `id`) VALUES ('322', 'robert', 'NULL') ON DUPLICATE KEY UPDATE `id`='NULL';
For appending a number after name i would suggest using autoincrement column instead.
insert into Person (Number,Name)
select 123, IF(mn.MaxNumber is NULL,'Robert',concat('Robert',mn.MaxNumber+1))
from (SELECT 'foo') foo
left JOIN (select max(CONVERT(SUBSTR(Name,LENGTH('Robert')+1),UNSIGNED)) `MaxNumber`
from person where name rlike '^Robert[0-9]*$') mn on true
where Not Exists (select * from Person where Number=123)
Below is how my table is
create table tab (id INT, fullname varchar(100));
Data is
insert into tab values
(1,'Full Name 1'),
(2,'Full Name 2'),
(3,'Full Name 3'),
(4,'Full Name 4'),
(5,'Full Name 5'),
(6,'Full Name 6');
I want to update the table with fullname as My Full Name is + actuallfullname. e.g. data for id 1 should be My Full Name is Full Name 1.
Any idea how to get this done in one query?
Using below query, it would be executing n times as I have so many records.
UPDATE tab SET fullname='My Full Name is Full Name 1';
sqlfiddle
Use CONCAT.
UPDATE tab
SET fullname = CONCAT('My Full Name is ', fullname)
SQLFiddle Demo
You can use MySQL's CONCAT() function:
UPDATE tab SET fullname = CONCAT('My Full Name is ', fullname);
But does this really belong in the database? Sounds like something one would normally perform at the presentation layer of one's application.
Ref CONCAT
UPDATE tab SET fullname=CONCAT('My Full Name is ',fullname);
UPDATE tab SET fullname = CONCAT('My Full Name is ' , fullname)