I have the following table:
+-----------+--------+
| FirstName | Active |
+-----------+--------+
| Rob | TRUE |
| Jason | TRUE |
| Mike | FALSE |
+-----------+--------+
I would like to insert 'John' (with Active=True) only if an entry for John doesn't exist already where Active=True. I try the following:
insert into testTable (FirstName, Active) values ('John',True) where not exists (select 1 from testTable where FirstName='John' and Active=True)
but i get
'Query input must contain at least one table or query'.
Can anybody help with what I am trying to achieve?
You can't combine Values with a WHERE clause. You need to use INSERT INTO ... SELECT instead.
Since you don't want to insert values from a table, you need to use a dummy table. I use MSysObjects for that purpose (that's a system table that always exists and always contains rows):
INSERT INTO testTable (FirstName, Active)
SELECT 'John', True
FROM (SELECT First(ID) From MSysObjects) dummy
WHERE NOT EXISTS (select 1 from testTable where FirstName='John' and Active=True)
In my case the field already exist in the table so I changed it from an INSERT to an UPDATE query and it worked.
Related
My current code is given below. I wanted to call all the columns from the table using * but the idcastncrew column name should display like castncrewid. In the requirement code, it's not working though, I wish there was a solution for my requirement such as the sample Requirement code.
Current code:-
SELECT idcastncrew AS castncrewid,castncrewname,castncrewtype,castncrewrole,imagelink,vendor,mode FROM subscriber;
Requirement :-
SELECT idcastncrew AS castncrewid, * FROM subscriber;
The closest I think you can get is to have the renamed column twice, once with the new name and once with the old name.
While MySQL does not allow * after an aliased column (causing your second code snippet to give an error), it does allow table.* anywhere...
SELECT idcastncrew AS castncrewid, subscriber.*
FROM subscriber;
To re-iterate; you'll still get a idcastncrew column, but you will ALSO get a castncrewid column.
There is no way to say don't include *this* column when using * in MySQL
https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=c69c537e46ad29e3c0c8c03d3ebd1bf7
You can alias columns when you alias the table, example as follows
MariaDB [DEV]> create table xxx (id int, str varchar(20));
MariaDB [DEV]> insert into xxx values (1, 'hi');
MariaDB [DEV]> insert into xxx values (2, 'Hello');
MariaDB [DEV]> insert into xxx values (3, 'World');
MariaDB [DEV]> insert into xxx values (4, 'Goodbye');
MariaDB [DEV]> select a.id as id1, a.* from xxx a order by 1;
+------+------+---------+
| id1 | id | str |
+------+------+---------+
| 1 | 1 | hi |
| 2 | 2 | Hello |
| 3 | 3 | World |
| 4 | 4 | Goodbye |
+------+------+---------+
I have search already an answer but i can't find one that is good for my situation.
I have a table called Names like this
ID NAME Age
1 Paula 20
2 Mark 17
And i want to run this sql
Insert into table names(name,age) values ("Chriss",15)//should be inserted
Insert into table names(name,age) values ("Mark",17)// should be ignored
Insert into table names(name,age) values ("Andrea",20) //should be inserted
So how can I ignore second insert query
Create a constraint that demands NAME and Age to be unique in the table.
ALTER TABLE `tablename` ADD UNIQUE `unique_index`(`NAME`, `Age`);
You would either need to Add UNIQUE constraint or check the data at the run time (if you don't have a permission to change table schema):
ALTER TABLE `Table_name`
ADD UNIQUE INDEX (`NAME`, `AGE`);
You can use:
INSERT INTO names(name,age)
SELECT * FROM (SELECT 'Chriss', 15) AS tmp
WHERE NOT EXISTS (
SELECT name FROM names WHERE name = 'Chriss' AND age = 15
) LIMIT 1;
An other way is just make the columns name and age UNIQUE so the query fails.
Change your query to this:
Insert into table names(name,age)
SELECT "Chriss",15 WHERE NOT EXISTS (SELECT 1 FROM names WHERE `name` = "Chriss");
Insert into table names(name,age)
SELECT "Mark",17 WHERE NOT EXISTS (SELECT 1 FROM names WHERE `name` = "Mark");
Insert into table names(name,age)
SELECT "Andrea",20 WHERE NOT EXISTS (SELECT 1 FROM names WHERE `name` = "Andrea");
First create a unique constraint for the columns NAME and Age:
ALTER TABLE names ADD UNIQUE un_name_age (`NAME`, `Age`);
and then use INSERT IGNORE to insert the rows:
Insert ignore into names(name,age) values
("Chriss",15),
("Mark",17),
("Andrea",20);
So if you try to insert a duplicate name the error will just be ignored and the statement will continue with the next row to insert.
See the demo.
Result:
| ID | NAME | Age |
| --- | ------ | --- |
| 1 | Paula | 20 |
| 2 | Mark | 17 |
| 3 | Chriss | 15 |
| 4 | Andrea | 20 |
Let's say I have this table
ID | Name | Hobby
---------------------------
1 | Alex | fishing
2 | Alex | soccer
3 | Nick | bike
4 | George | hike
ID - is unique. Hobby - is NOT unique (need to keep it as non-unique)
Inserting a record:
INSERT INTO my_table (ID, Name, Hobby) VALUES ('5', 'Christina', 'bike')
How to modify the query, if I need to insert the record if bike value does not exist at all in Hobby column?
Anotherwords:
VALUES ('5', 'Christina', 'bike') - would NOT be inserted as 3 | Nick | bike exists
VALUES ('5', 'Christina', 'cooking') would be inserted as cooking is not present in Hobby column at all.
Having existing database with thousands of records, there is a risk that there are duplicates already in Hobby...
But from now on.. when adding new records, I want to avoid adding if already exists..
Thank you.
The easiest solution could be changing hobby column to unique. This way you will force your database to only insert unique hobbies. Another solution could be using triggers fore before insert / update.
Based on MySQL: Insert record if not exists in table
But with some corrections (to fix the duplicate errors)
The following query works for me.
INSERT INTO my_table (ID, Name, Hobby)
SELECT * FROM (SELECT '5' AS ID, 'Christina' AS Name, 'cooking' AS Hobby) AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE Hobby= 'cooking'
) LIMIT 1;
table users as below
--------------------
portal_id | user_id
1 | 100
1 | 101
1 | 102
1 | 103
---------------------
SELECT group_concat(user_id) as toUserIds FROM users where portal_id=1;
after am getting in toUserIds is 100,101,102,103
after i want insert doc_user_xref table as below(same doc id with different user id )
insert into doc_user_xref(doc_id,user_id)values(5211,100);
insert into doc_user_xref(doc_id,user_id)values(5211,101);
insert into doc_user_xref(doc_id,user_id)values(5211,102);
insert into doc_user_xref(doc_id,user_id)values(5211,103);
In above insert value i need loop or iterator.
Don't use GROUP_CONCAT(), just use INSERT ... SELECT:
INSERT INTO doc_user_xref
(doc_id, user_id)
SELECT 5211, user_id
FROM users
WHERE portal_id = 1
I have a CSV file containing user information:
'Arlington', '1,3,5,7,9'
'StackExchange', '2,3'
And I will need the above information imported like this:
"User" table:
id | name
1 | 'Arlington'
2 | 'StackExchange'
"User groups" table:
id | user_id | group_id
1 | 1 | 1
2 | 1 | 3
3 | 1 | 5
4 | 1 | 7
5 | 1 | 9
6 | 2 | 2
7 | 2 | 3
What's the easiest way to do this? I have imported the data with a temp column holding the CSV values:
id | name | tmp_group_ids
1 | 'Arlington' | '1,3,5,7,9'
2 | 'StackExchange' | '2,3'
I am thinking if I import it this way, I will know exactly what id gets assigned for the user (the id column in the users table is auto_increment), and so I can use that id as user_id for the "user groups" table.
But now how do I get values from tmp_group_ids into the "User groups" table?
Would appreciate any help! Thanks!
the easy way would be a php or perl script.
You can use the MySQL SUBSTRING() function to split the string and insert the different values into the table. You can do this by writing a function or using a stored procedure.
I had recently a similar problem, I used the function SUBSTRING_INDEX(str,delim,count), using "," as delimiter
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index
INSERT INTO tableUserGroup (userid, groupid)
SELECT
t1.id
, substring_index(t1.tmp_group_ids,',',2)
, substring_index(t1.tmp_group_ids,',',3)
FROM table1 t1
First, insert the names into the User table - with id autonumber, this will work:
INSERT INTO User
(name)
SELECT DISTINCT
name
FROM TempTable
Then:
--- Create a "numbers" table:
CREATE TABLE num
( i INT PRIMARY KEY
) ;
--- Populate it with numbers:
INSERT INTO num
(i)
VALUES
(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);
Then, you can use FIND_IN_SET() function which is handy for this situation (splitting comma-separated fields), like this:
INSERT INTO User_Groups
(user_id, group_id)
SELECT
u.id AS user_id
, num.i AS group_id
FROM User AS u
JOIN TempTable AS t
ON t.name = u.name
JOIN num
ON FIND_IN_SET(num.i, t.tmp_group_ids) > 0