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;
Related
I have tables for multiple stations with data from each station: timestamp, error etc. The total number of rows in each table is the frequency of errors at that station. The name of the station is in the table name.
CREATE TABLE Station_00 (error INT, timestamp DATETIME);
INSERT INTO Station_00 VALUES (1, '2020/10/05 12-12-12'),(2,'2020/10/05 12-12-15'),(3,'2020/10/05 12-12-20'),(4,'2020/10/05 12-12-25'),(5,'2020/10/05 12-12-30'),(6,'2020/10/05 12-12-35'),(7,'2020/10/05 12-12-37'),(8,'2020/10/05 12-12-40');
CREATE TABLE Station_01 (error INT, timestamp DATETIME);
INSERT INTO Station_01 VALUES (1, '2020/10/05 12-14-12'),(2,'2020/10/05 12-14-15'),(3,'2020/10/05 12-14-20'),(4,'2020/10/05 12-14-25');
CREATE TABLE Station_02 (error INT, timestamp DATETIME);
INSERT INTO Station_02 VALUES (1, '2020/10/05 12-14-17'),(2,'2020/10/05 12-14-20'),(3,'2020/10/05 12-14-26'),(4,'2020/10/05 12-14-29'),(5,'2020/10/07 12-14-29');
CREATE TABLE Station_03 (error INT, timestamp DATETIME);
INSERT INTO Station_03 VALUES (1, '2020/10/05 12-17-12'),(2,'2020/10/05 12-17-15'),(3,'2020/10/07 12-14-20'),(4,'2020/10/07 12-14-25'),(5,'2020/10/07 12-14-30'),(6,'2020/10/07 12-16-25');
Event values are random, not necessarily in ascending order like here.
I want to create a VIEW with as many rows as there are stations and columns station (the name of each table) and frequency (the number of rows in each table). Is there any way to do that in one SELECT ?
I would like something like:
+---------+-----------+
| Station | Frequency |
+---------+-----------+
| 00 | 8 |
| 01 | 4 |
| 02 | 5 |
| 03 | 6 |
+---------+-----------+
You could use union all:
create view myview as
select '00' as station, count(*) as cnt from table_station00
union all select '01', count(*) from table_station01
union all select '02', count(*) from table_station02
Note, however, that all these tables should probably be consolidated in a single table, with an additional column that represents the station. Then, you could just do:
select station, count(*) cnt from table_station;
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 |
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.
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
Let's say I have two tables:
Table 1 has the columns NOTE_ID (a unique key) and NOTE_BODY (a big text blurb).
Table 2 has the columns KEYWORD_ID (a unique key) and KEYWORD (a keyword).
I want to get a result set that tells me which keywords each NOTE_BODY contains, without nesting a bunch of loops. So ideally I would get a row for each NOTE_BODY-KEYWORD match.
What's the right way to go about this? I'm unsure if a JOIN+LIKE'%%' does the trick, or if I should be using full-text indexing. Any help much appreciated...
A full text indexing solution is the right way to do this, if you plan to have many rows. You could use MySQL's native solution if you are using the MyISAM storage engine, but you could also consider the popular third-party search engines Sphinx and Apache Lucene.
On the other hand, a simple INNER JOIN would have done the trick:
SELECT t1.note_id, t1.note_body, t2.keyword
FROM table_1 t1
JOIN table_2 t2 ON (t1.note_body LIKE CONCAT('%', t2.keyword, '%'));
Test case:
CREATE TABLE table_1 (note_id int, note_body varchar(100));
CREATE TABLE table_2 (keyword_id int, keyword varchar(50));
INSERT INTO table_1 VALUES (1, 'Hello Stack Overflow');
INSERT INTO table_1 VALUES (2, 'Hello World');
INSERT INTO table_1 VALUES (3, 'Hello, my name is Daniel');
INSERT INTO table_1 VALUES (4, 'Goodbye');
INSERT INTO table_2 VALUES (1, 'Hello');
INSERT INTO table_2 VALUES (2, 'name');
Result:
+---------+--------------------------+---------+
| note_id | note_body | keyword |
+---------+--------------------------+---------+
| 1 | Hello Stack Overflow | Hello |
| 2 | Hello World | Hello |
| 3 | Hello, my name is Daniel | Hello |
| 3 | Hello, my name is Daniel | name |
+---------+--------------------------+---------+
4 rows in set (0.00 sec)