Inserting values in Mysql table if all the columns have different values - mysql

I am working on a blogging site but problem which I am facing is that, I want to allow user to create a blog if and only if his/her combination of email address, Blog Name and Blog Title is different from any other rows in the table. For example let us consider this table:-
Email BlogName BlogTitle
abc#gmail.com Coder's world What is coding?
abc#gmail.com Sql world What is sql?
Now if a user tries to enter a values('abc#gmail.com','Coder's Worlds' ,'What is coding?') in the table again then he/she will not be allowed to do so. But if the user tries to insert different combination of email, BlogName and BlogTitle then he/she will be allowed to do so.
As I am pretty new to Mysql, I don't know how to do this, so please help me to do this.
My Table structure :-

You can add a unique constraint on the combination of the three columns:
ALTER TABLE `blog_table` ADD UNIQUE `unique_index`(`Email`(100), `BlogName`(100), `BlogTitle`(100));
This will also remove any duplicates which might already exist in your blog table.
Note that this constraint uses only the first 100 characters from each of the three columns to avoid the #1071-Specified key was too long error.

Make those 3 Columns unique.
Here is a example of Making multiple fields composite
ALTER TABLE table ADD UNIQUE ('field_1','field_2', 'field_3');

IF (SELECT 1 = 1 FROM Table WHERE Email=#email and BlogName=#blogname and BlogTitle=#blogtitle) THEN
BEGIN
#return error message do not insert
END;
ELSE
BEGIN
#insert logic here
END;
END IF;
Check if matching record exists in table before inserting using above code

Related

Is it possible in MySql to associate inserted data to a specific user?

I just was wondering if is it possible to associate an user to the data inserted in a table.
For example:
I have a table Customers with columns customerID, name and address. Is there any method in MySql to know what user has inserted each row in the table or must I add a column userID in the table Customer to add the user in my SQL Insert statement?.
If I have only one table, it is not a proble to add the userID column. But when i have multiple tables, maybe it becomes a messy task.
Thanx in advance.
If you are trying to find out the user_id caused the insert then NO, there is no other way than you storing it explicitly likewise you already have thought of.
If there is multiple tables for which you want to store the same information; then you can probably have a separate table where you can have the user_id column and can use a AFTER INSERT TRIGGER to insert the user id in this table.
No, no such functionality is provided by MySQL. You'll have to add a column for user_id in your table(s) and insert the user id yourself.

How to insert values of one table into another

I have two tables user and friends where users from user table can become friends.I have inserted 3 users into user table,now i want to make friends out of for example user_id = 1 and user_id = 2 but i don't know how to add this two id's in friends table.Photos of these two tables are attached.
... I don't really know what software you are using, but what you need is to declared a foreign key "UserId" column in your friend's table. Once that is done you can insert data in anyway possible by either using Mysql or a simple SQL insert:
INSERT INTO `friend`(UserId) VALUES (1)

enter data into 2 tables with foriegn key relation based on one attribute of primary table

I have a table 'project' that has attributes:name, UID(PK), section(distinguisher)... and 3 tables A,B,C based on section with specific properties of each section.i want to be able to enter data into project and the section specific data into A/B/C TABLE based on entry in section attribute of project table of that row. all tables have Foreign key with UID as UID_A, UID_B, UID_C...any ideas on how i can do it? all help appreciated as i am quite a novice...thanks! I am working with Mysql workbench.
Well, create a trigger on the table project:
CREATE TRIGGER `fill_abc` AFTER INSERT ON `project`
FOR EACH ROW BEGIN
INSERT INTO A <some specific data...>;
INSERT INTO B <some specific data...>;
INSERT INTO C <some specific data...>;
END;
Probably, you want to handle not only inserts into this table, but updates and deletes as well - it is nearly the same idea. See trigger definition here and examples here

mysql create table based on columns from another table and auto updated

I could have the wording 'wrong' here (new to mysql) but i hope i've explained what I'm trying to do well.
i have a table called submissions with 4 fields submitId, studentName, submitDate, status
status refers to whether they got admitted or not.
submitId is auto incremented
Now i wanted to create another table based on that, but only if the status is true, this new table would have the submitId, studentName, submitDate, plus additional fields.
this table would have a new auto increment studentId
how would i do that so it automatically updates any new entry to the first table on the second table, but not overwrite the additional content of table 2.
i thought of using a view, but u can't add new columns on the view, right?
do i have the logic wrong here or what are the options, could someone please point me in the right direction, thanks
You want to use a trigger. See:
http://dev.mysql.com/doc/refman/5.6/en/triggers.html
You can create the trigger so that when a row is inserted into submissions with status=true, it inserts a row into your new student table. It would look something like this:
delimiter //
CREATE TRIGGER sub_ins_check AFTER INSERT ON submissions
FOR EACH ROW
BEGIN
IF NEW.status = 1 THEN
INSERT INTO your_new_table (student_name, submit_date, submit_id) VALUES (NEW.student_name, NEW.submit_date, NEW.submit_id);
END IF;
END;//
delimiter ;
Then create another trigger so that when a row is updated in submissions, it updates the row with the same submit_id in your new table, like this:
delimiter //
CREATE TRIGGER sub_ins_check AFTER UPDATE ON submissions
FOR EACH ROW
BEGIN
IF NEW.status = 1 THEN
UPDATE your_new_table SET student_name = NEW.student_name, submit_date = NEW.submit_date, (etc..)) WHERE submit_id = NEW.submit_id;
END IF;
END;//
delimiter ;
I think your data model is wrong. Remember that student my have several submissions and there may be number of students with the same name. You must distinguish them.
Is there any reason you want to duplicate student data in both tables?
If you're new to SQL, read about table normalization first.
In you Student table you should store students data and in Submission table - guess what :)
The first thing you need to do is step back and consider the problem from the perspective of logical entities.
You've identified two entities that I can see - student and submission. "Student" is an obvious entity which you may choose NOT to store in your database, but it may be better that you do. "Submission" is a more obvious one, but what is not so obvious is what a "submission" actually is. Let's assume it is some sort of transaction.
You've mentioned a "second table" without a clear indication of its role in the solution. The best I could infer is that it is meant to be some sort of historical trail on activity against a submission. If true, then I could envision a physical schema sketched out as follows:
Student table. One row per student; contains information about a student (name, id, etc.). Primary key would probably be an auto-incremented number.
Submission table. One row per submission; includes a foreign key to the student table (referencing the primary key); has its own primary key, also an auto-incremented integer. Also has triggers defined for INSERT and UPDATE. INSERT trigger causes INSERT into submission_log table; UPDATE trigger also causes INSERT into submission_log table.
Submission_log table. One row per event against the submission table. Includes all the fields of submission plus its own primary key (submission's primary key is a foreign key here), and includes an indicator field for whether it represents an insert or update on submission.
The purpose of the above is not to supply a solution, or even the framework of a solution, but rather to get you to think in terms of the logical entities you want to model in your solution, and their relationships to each other. When you have a clear picture of the logical model, it will be much easier to determine what tables are required, what their roles are, and how they will be used and how they will relate to each other.

Increment a database field by 1

With MySQL, if I have a field, of say logins, how would I go about updating that field by 1 within a sql command?
I'm trying to create an INSERT query, that creates firstName, lastName and logins. However if the combination of firstName and lastName already exists, increment the logins by 1.
so the table might look like this..
firstName----|----lastName----|----logins
John Jones 1
Steve Smith 3
I'm after a command that when run, would either insert a new person (i.e. Tom Rogers) or increment logins if John Jones was the name used..
Updating an entry:
A simple increment should do the trick.
UPDATE mytable
SET logins = logins + 1
WHERE id = 12
Insert new row, or Update if already present:
If you would like to update a previously existing row, or insert it if it doesn't already exist, you can use the REPLACE syntax or the INSERT...ON DUPLICATE KEY UPDATE option (As Rob Van Dam demonstrated in his answer).
Inserting a new entry:
Or perhaps you're looking for something like INSERT...MAX(logins)+1? Essentially you'd run a query much like the following - perhaps a bit more complex depending on your specific needs:
INSERT into mytable (logins)
SELECT max(logins) + 1
FROM mytable
If you can safely make (firstName, lastName) the PRIMARY KEY or at least put a UNIQUE key on them, then you could do this:
INSERT INTO logins (firstName, lastName, logins) VALUES ('Steve', 'Smith', 1)
ON DUPLICATE KEY UPDATE logins = logins + 1;
If you can't do that, then you'd have to fetch whatever that primary key is first, so I don't think you could achieve what you want in one query.
This is more a footnote to a number of the answers above which suggest the use of ON DUPLICATE KEY UPDATE, BEWARE that this is NOT always replication safe, so if you ever plan on growing beyond a single server, you'll want to avoid this and use two queries, one to verify the existence, and then a second to either UPDATE when a row exists, or INSERT when it does not.
You didn't say what you're trying to do, but you hinted at it well enough in the comments to the other answer. I think you're probably looking for an auto increment column
create table logins (userid int auto_increment primary key,
username varchar(30), password varchar(30));
then no special code is needed on insert. Just
insert into logins (username, password) values ('user','pass');
The MySQL API has functions to tell you what userid was created when you execute this statement in client code.
I not expert in MySQL but you probably should look on triggers e.g. BEFORE INSERT.
In the trigger you can run select query on your original table and if it found something just update the row 'logins' instead of inserting new values.
But all this depends on version of MySQL you running.