MySql enter duplicate rows into table - mysql

I would like to enter two of the same emails as two different rows into MySQL table Person. However, it keeps only one row. How do I modify my code? Thanks.
create table if not exists Person (
Id int auto_increment primary key,
Email varchar(20)
);
insert into Person(Email)
values ('abc#efg.com'),
('abc#efg.com')
;

Your query looks ok
SQL fiddle demo
OUTPUT
| Id | Email |
|----|-------------|
| 1 | abc#efg.com |
| 2 | abc#efg.com |

Related

What is the difference between LIKE and AS SELECT * FROM in duplicating a table in mysql?

I'm trying to practice sql using w3resource's sample activities. They gave an answer to that activity but they do not have further explanation on to why they used a specific script, and I want to know what would be the difference when I would do this.
Write a SQL statement to create the structure of a table dup_countries similar to countries.
Answer:
CREATE TABLE IF NOT EXISTS dup_countries LIKE countries;
Output:
mysql> DESC dup_countries;
+--------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| COUNTRY_ID | varchar(2) | YES | | NULL | |
| COUNTRY_NAME | varchar(40) | YES | | NULL | |
| REGION_ID | decimal(10,0) | YES | | NULL | |
+--------------+---------------+------+-----+---------+-------+
3 rows in set (0.03 sec)
Write a SQL statement to create a duplicate copy of countries table including structure and data by name dup_countries.
Answer:
CREATE TABLE IF NOT EXISTS dup_countries AS SELECT * FROM countries;
Output:
mysql> DESC dup_countries;
+--------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+---------------+------+-----+---------+-------+
| COUNTRY_ID | varchar(2) | YES | | NULL | |
| COUNTRY_NAME | varchar(40) | YES | | NULL | |
| REGION_ID | decimal(10,0) | YES | | NULL | |
+--------------+---------------+------+-----+---------+-------+
3 rows in set (0.11 sec)
You can of course check the documentation (CREATE TABLE ... LIKE Statement, CREATE TABLE ... SELECT Statement) but there're two main differences:
CREATE TABLE LIKE creates an empty table, while CREATE TABLE SELECT inserts selected rows.
CREATE TABLE LIKE copies source table definitions, indexes included, while
CREATE TABLE SELECT figures out column types from actual data found (you don't necessarily have a source table to begin with, it can be any kind of dynamically generated result-set) and also allows you set the types manually.
We can Clone Table using two ways:
using Like
using As Select * from TableName.
1st Way:
CREATE TABLE new_table AS SELECT * FROM original_table;
It inherits only basic definitions,null settings and default values.
But doesnt inherit indexes and auto increment definitions.
It copy just structure and data.
2nd Way:
CREATE TABLE new_table LIKE original_table;
Inherit all table definitions without Data.
If we wants Data,we can use
INSERT INTO new_table SELECT * FROM original_table;
CREATE TABLE IF NOT EXISTS dup_countries LIKE countries;
is not equal to
CREATE TABLE IF NOT EXISTS dup_countries AS SELECT * FROM countries;
The main difference - 2nd query adds rows into newly created table whereas 1nd one creates empty table.
You may eliminate this difference by adding a condition to 2nd query:
CREATE TABLE IF NOT EXISTS dup_countries AS SELECT * FROM countries WHERE FALSE;
Both 1st and 3rd query produces the same result - empty table.
But the differences exists nevertheless. And they may be critical.
1st query copies a lot of constructions into the table-copy. Indices. Constraints (including NOT NULL, PRIMARY KEY...). Comments. And so on... And even generated columns definitions.
Whereas 2nd and 3rd queries creates "cleared" structure - only base properties are reproduced.
https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=7bbebd3667bd333f1ca55edfeac04ae8
PS. And none query copies foreign keys and triggers.

How to insert row with next id in mysql

I'm using mysql 8 and I'm a big noob so be polite please, I have a table with only 2 columns, ID (Primary key, Not Null, Auto Increment, Unique) and Password (Not Null, Unique)
I'd like to have something like this:
+----+------------+
| id | Password |
+----+------------+
| 1 | dsakjhsajs |
+----+------------+
| 2 | xczkcjhczx |
+----+------------+
| 3 | treiuytreu |
+----+------------+
Is it possible to INSERT a new password without specifying the id and let the db calculate the id?
Because if I use
INSERT INTO myTable VALUES ('anotherpassword')
I obviously get an error
Name the columns for which you will be inserting values:
INSERT into mytable (passwordcol) VALUES ('password1');
The word "password" is a keyword, so avoid that as a column name.
insert has a syntax to specify columns:
INSERT INTO myTable(`Password`) VALUES ('anotherpassword')
ps. Don't store clear text passwords.

Get the auto increment-primary key column programatically

witch is the auto increment field in a mysql table?
I have a table structure, for example:
table name is my_table and the fields are my_id, my_name, my_blah.. The one of fields is an auto incremented primary key. Witch is it?
How can I get the name of auto increment field on this table with a php code and/or a mysql query?
You can use the MySQL SHOW COLUMNS query to retrieve information about the columns in a table:
mysql> SHOW COLUMNS FROM `test`;
+----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| col1 | varchar(100) | YES | | NULL | |
| col2 | int(11) | YES | | NULL | |
+----------+--------------+------+-----+---------+----------------+
The extra column will contain auto_increment for the primary key field.
You could try with a
SHOW COLUMNS FROM TableName
See here: http://dev.mysql.com/doc/refman/5.0/en/show-columns.html
Use a MySQL client and issue the query SHOW CREATE TABLE my_table.
It shows you the code one needs to run to create that table. You can see the column names, types (and lengths), other attributes each column may have (they depend on the type). AUTO_INCREMENT is such an attribute.
It also shows you the PK and the indexes of the table.

Insert Into.. Select.. On Duplicate Key Update

I'm trying to test how the insert into duplicate key works. And currently this is what I did:
INSERT INTO
user_test (userName, first, last)
SELECT
u.userName, u.first, u.last
FROM otherdatabase.user as u
ORDER BY u.userName ASC
ON DUPLICATE KEY UPDATE
userName = u.userName
I executed this query and it worked and inserted rows. Then what I did was I modified one row from the user table and then tried to run this query again, but instead of just updating that one row it inserted all the rows again.
From what I understand shouldn't it just update that one row I modified from the user table?
What I'm trying to do is do a "Insert if it doesn't exist and update if it exist" query and found that using insert into .. on duplicate key can do that but I'm obviously doing it wrong...
CREATE TABLE user_test (
id bigint(20) NOT NULL AUTO_INCREMENT,
userName varchar(20) DEFAULT NULL,
first varchar(20) DEFAULT NULL,
last varchar(20) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=64 DEFAULT CHARSET=latin1
Per Barranka's suggestion I added a unique index to the user_name column
Alter table user_test add unique index idx_userName(userName)
Then I ran the query again and it didn't add any more rows since its already existing..
This is an example of what the user_table looks like now, its now the same on the users table.
user_table:
userName | first | last |
ckeith | Carl | Keith |
mmonroe | Mickey | Monroe |
Then what I did to test it again is from the user table I modified one of the rows
user:
userName | first | last |
ckeithh | Carl | Keith |
mmonroe | Mickey | Monroe |
and executed the query again, this is now what the users_table looks like:
user_table:
userName | first | last |
ckeith | Carl | Keith |
mmonroe | Mickey | Monroe |
ckeithh | Carl | Keith |
I thought it would just update the first row to ckeithh but it just inserted one row?
My expected output was:
user_table:
userName | first | last |
ckeithh | Carl | Keith |
mmonroe | Mickey | Monroe |
Update:
I added a unique index and made sure that it is unique. The inserting works but now the update is not working. Anything else i should try?
Still not able to get this to work, I have confirmed that the column i'm using is unique and that my version of mysql is v5 (i saw on one of the forums that for this to work mysql should be v5, not sure if thats real or not, but still i checked and im using v5.5.37)

how to get rows from table which are not mentioned in another table

i got 2 tables with following structure:
CREATE TABLE users(
id bigint not null auto_increment,
name varchar(255) default '',
primary key(id)
);
CREATE TABLE user_links(
user_id bigint,
job_id bigint
);
so users are linked to jobs (jobs table structure is not needed for this question)
i need to get all users which are not linked to any job at one time using one query
for example, if i have tables with such data:
users:
id | name
1 | james
2 | fred
user_links:
user_id | job_id
1 | 5
1 | 6
then i need result rows like this:
id | name
2 | fred
... assuming there are no NULL user_id in user_links:
SELECT *
FROM users
LEFT OUTER JOIN user_links ON users.id = user_links.user_id
WHERE user_links.user_id IS NULL
SELECT *
FROM users
WHERE id NOT IN (SELECT user_id
FROM user_links)