I have table that doesn't need a specific field to be the primary key. I could add a auto-increment ID field, but it won't be used at all within database queries...
Can I make a UNIQUE KEY to be primary too?
the UNIQUE KEY consists of two fields paired together:
a VARCHAR(64) NOT NULL,
b VARCHAR(64) NOT NULL,
UNIQUE KEY uk_ab(a,b)
Sure (no need for UNIQUE KEY):
PRIMARY KEY (a, b)
Have a look at the documentation:
A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL declares them so implicitly (and silently). A table can have only one PRIMARY KEY. The name of a PRIMARY KEY is always PRIMARY, which thus cannot be used as the name for any other kind of index.
and
A PRIMARY KEY can be a multiple-column index. However, you cannot create a multiple-column index using the PRIMARY KEY key attribute in a column specification. Doing so only marks that single column as primary. You must use a separate PRIMARY KEY(index_col_name, ...) clause.
Not sure if this would work...
PRIMARY KEY uk_ab(a,b)
If your table already has a unique constraint, then you need to add primary key (ALTER TABLE [table_name] ADD CONSTRAINT [constraint_name] PRIMARY KEY (a,b)), and drop the existing unique constraint. Otherwise, you will have 2 unique indexes on the same columns.
If you create a new table, use PRIMARY KEY(a,b) instead of UNIQUE(a,b) as proposed by others.
Related
I am trying to drop the existing primary keys and add two new primary primary keys in an existing database table using the following query:
ALTER TABLE `match_team_recruit` DROP PRIMARY KEY,
ADD PRIMARY KEY (`ind_stnum`, `team_send`);
However, I get the following error when running the query.
#1062 - Duplicate entry '183-0' for key 'PRIMARY'
Please see attached Image below:
Can anyone advise how I can solve this?
A primary key in MySQL has to follow these three rules.
A primary key must contain unique values. If the primary key consists of multiple columns, the combination of values in these columns must be unique.
A primary key column cannot contain NULL values. It means that you have to declare the primary key column with the NOT NULL attribute. If you don’t, MySQL will force the primary key column as NOT NULL implicitly.
A table has only one primary key.
Courtesy: Introduction to MySQL primary key
To fix your problem you should just add one Primary Key to your table. The Primary Key is used to distinguish Row's, therefor you can't have multiple Primary Key's in one table!
I have schedules table which contain student_id and class_id as it's foreign key. I know I can use syntax $table->primary(['student_id', 'class_id']) to prevent same foreign key to pair more than one time in a table, but the problem is my schedules table also has primary key called id, so I can't assign foreign key as primary (will get multiple primary key error). Is there any better approach to solve my problem (make foreign key as primary so they'll never pair more than one time)?
Thanks..
i've tried to set the primary and foreign key using the method that i learn at http://fellowtuts.com/php/setting-up-foreign-key-in-phpmyadmin/ but an error came up stating that
#1025 - Error on rename of '.\sistem_akaun\#sql-1b70_7d' to '.\sistem_akaun\detail_akaun' (errno: 150 - Foreign key constraint is incorrectly formed)
can i know what's the problem here?sorry if this question sounds stupid,just a newbie
Check to make sure that the Primary Key you are referencing exists. If, in your main table, you have id_main = 0 on your main table, where id_main is a foreign key referencing id_ref (which is the primary key of the other table) but you have reference ref_id = 1 and no 0 value, you will get an error.
Check to make sure your foreign key is the primary key of the other table.
Check to make sure they are the same data type, length, unsigned status. Sometimes these matter sometimes not.
Sometimes I've had trouble where both Foreign Key and Primary Key are both named "id". This can be a problem depending on what software/methods you are using.
You may find it easier to specify a foreign key manually, in SQL.
ALTER TABLE Table
ADD FOREIGN KEY (Column)
REFERENCES TableToReference (ColumnToReference)
(Where Table is the table you wish to add a foreign key to)
#itsfawwaz, You can also do this by below way. Check below example.
Example : (Table Orders)
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
PRIMARY KEY (O_Id),
CONSTRAINT fk_PerOrders FOREIGN KEY (P_Id)
REFERENCES Persons(P_Id)
)
Above is sample example, you can use your own table fields !
Let me know if still you have any issues.
Ok, so i'm a newbie here at SQL..
I'm settings up my tables, and i'm getting confused on indexes, keys, foreign keys..
I have a users table, and a projects table.
I want to use the users (id) to attach a project to a user.
This is what I have so far:
DROP TABLE IF EXISTS projects;
CREATE TABLE projects (
id int(8) unsigned NOT NULL,
user_id int(8),
name varchar(120) NOT NULL,
description varchar(300),
created_at date,
updated_at date,
PRIMARY KEY (id),
KEY users_id (user_id)
) ENGINE=InnoDB;
ALTER TABLE projects (
ADD CONSTRAINT user_projects,
FOREIGN KEY (user_id) REFERENCES users(id),
ON DELETE CASCADE
)
So what I'm getting lost on is what is the differences between a key, an index, a constraint and a foreign key?
I've been looking online and can't find a newbie explanation for it.
PS. I'm using phpactiverecord and have the relationships set up in the models
user-> has_many('projects');
projects -> belongs_to('user');
Not sure if that has anything to do with it, but thought i'd throw it in there..
Thanks.
EDIT:
I thought it could possible be something to do with Navicat, so I went into WampServer -> phpMyAdmin and ran this...
DROP TABLE IF EXISTS projects;
CREATE TABLE projects (
id int(8) unsigned NOT NULL,
user_id int(8) NOT NULL,
name varchar(120) NOT NULL,
description varchar(300),
created_at date,
updated_at date,
PRIMARY KEY (id),
KEY users_id (user_id),
FOREIGN KEY (user_id) REFERENCES users(id)
) ENGINE=InnoDB;
Still nothing... :(
Expanding on Shamil's answers:
INDEX is similar to the index at the back of a book. It provides a simplified look-up for the data in that column so that searches on it are faster. Fun details: MyISAM uses a hashtable to store indexes, which keys the data, but is still linearly proportional in depth to the table size. InnoDB uses a B-tree structure for its indexes. A B-tree is similar to a nested set - it breaks down the data into logical child groups, meaning search depth is significantly smaller. As such, lookups by ranges are faster in a InnoDB, whereas lookups of a single key are faster in MyISAM (try to remember the Big O of hashtables and binary trees).
UNIQUE INDEX is an index in which each row in the database must have a unique value for that column or group of columns. This is useful for preventing duplication, e.g. for an email column in a users table where you want only one account per email address. Important note that in MySQL, an INSERT... ON DUPLICATE KEY UPDATE statement will execute the update if it finds a duplicate unique index match, even if it's not your primary key. This is a pitfall to be aware of when using INSERT... UPDATE statements on tables with uniques. You may wind up unintentionally overwriting records! Another note about Uniques in MySQL - per the ANSI-92 standard, NULL values are not to be considered unique, which means you can have multiple NULL values in a nullable unique-indexed column. Although it's a standard, some other RDBMSes differ on implementation of this.
PRIMARY KEY is a UNIQUE INDEX that is the identifier for any given row in the table. As such, it must not be null, and is saved as a clustered index. Clustered means that the data is written to your filesystem in ascending order on the PK. This makes searches on primary key significantly faster than any other index type (as in MySQL, only the PK may be your clustered index). Note that clustering also causes concerns with INSERT statements if your data is not AUTO_INCREMENTed, as MySQL will have to shift data around on the filesystem if you insert a new row with a PK with a lower ordinal value. This could hamper your DB performance. So unless you're certain you know what you're doing, always use an auto-incremented value for your PK in MySQL.
FOREIGN KEY is a reference to a column in another table. It enforces Referential Integrity, which means that you cannot create an entry in a column which has a foreign key to another table if the entered value does not exist in the referenced table. In MySQL, a FOREIGN KEY does not improve search performance. It also requires that both tables in the key definition use the InnoDB engine, and have the same data type, character set, and collation.
KEY is just another word for INDEX.
A UNIQUE index means that all values within that index must be unique, and not the same as ant other within that index. An example would be an Id column in a table.
A PRIMARY KEY is a unique index where all key columns must be defined as NOT NULL, i.e, all values in the index must be set. Ideally, each table should have (and can have) one primary key only.
A FOREIGN KEY is a referential constraint between two tables. This column/index must have the same type and length as the referred column within the referred table. An example of a FOREIGN KEY is a userId, between a user-login table and a users table. Note that it usually points to a PRIMARY KEY in the referred table.
http://dev.mysql.com/doc/refman/5.1/en/create-table.html
In Symfony2 doc 'How to use PdoSessionStorage to store Sessions in the Database', which show the session table like this:
CREATE TABLE `session` (
`session_id` varchar(255) NOT NULL,
`session_value` text NOT NULL,
`session_time` int(11) NOT NULL,
PRIMARY KEY (`session_id`),
UNIQUE KEY `session_id_idx` (`session_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Why unique key constraint is needed for the primary key?
A primary key is by definition a unique key. In this example, it's just a duplicated unecessary key.
In other cases, where the primary key could potentially be composite (consisting of two or more fields), such secondary indexes would allow the individual components of the primary key to be addressed seperately.
For instance:
create table X {
a char,
b char,
primary key (a,b)
}
where you do a query with WHERE b=something, would not use the primary key index, as B's index entries are tied to 'a', and you're not using 'a' in the query. Adding a secondary seperate index dedicated to just B allows index use for this where clause.
Primary keys have to be unique by definition. (regardless of RDBMS)
A primary key is a combination of columns which uniquely specify a row.