I have a create database and have about 8 tables in Database also created Primary keys and foreign-keys in appropriate tables. But when I insert data in primary-table, my other table doesn't show updated data.
I mean, say I have a table which has data for names like ;
N is (name)
N1 = George, N2 = Ross, N3 = Rim ...etc now that means i have Primary key N1,N2,N3 etc..
Now, when I insert this primary keys in others table it should shows me name like George, ross and rim instead of primary-key number it self(N1,N2,N3).
How can I get names instead PK itself?
You are misunderstanding the concept of keys in relational databases. Keys are there, not to copy data from similar tables but to show the relations between data in different tables. They help to understand how the data between different tables is related - that is where the name "relational database" comes from. They also speed up querying of that data if indexed.
You can read more about the usage of keys here: Keys and normalization
I am still unclear on what exactly you want to do with the database. but let me demonstrate you on the basic of database and how you should be using it. Consider a table users where you will be storing the data related to user.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`email` varchar(50) DEFAULT NULL,
`phone` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`),
);
the column id holds the primary key and have an attribute called auto_increment, now what this means is every time you insert a record to this table the id attribute gets incremented and you don't have to worry about inserting any value in this column because your database will take care of that. for example take a look at insert query below.
INSERT INTO users(name,email,phone) VALUES('First Name', 'first#domain.com', '9999999999');
INSERT INTO users(name,email,phone) VALUES('Second Name', 'second#domain.com', '8888888888');
INSERT INTO users(name,email,phone) VALUES('Third Name', 'third#domain.com', '2222222222');
INSERT INTO users(name,email,phone) VALUES('Fourth Name', 'fourth#domain.com', '3333333333');
did you see you did not insert any id here. this is because it is database who will handle the logic. now the first record will hold the value 1 the second will have 2 the third one 3 and the fourth one 4 and so on.
hope this helps you.
Related
I am extending a product sales plugin and am trying to understand how wordpress handles database relations. I am building tables on activation using dbDelta. An example of a table schema would be:
$table_schema = [
"CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}plugin_orders` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`people_id` bigint(20) DEFAULT NULL,
`order_id` bigint(20) DEFAULT NULL,
`order_status` varchar(11) DEFAULT NULL,
`order_date` datetime DEFAULT NULL,
`order_total` decimal(13,2) DEFAULT NULL,
`accounting` tinyint(4) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `people_id` (`people_id`),
KEY `order_id` (`order_id`)
) $collate;",
"CREATE TABLE IF NOT EXISTS `{$wpdb->prefix}plugin_order_product` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`order_id` bigint(20) DEFAULT NULL,
`product_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `order_id` (`order_id`),
KEY `product_id` (`product_id`)
) $collate;"
];
I see that id in each table is the PRIMARY KEY but what does declaring the other KEYs actually do? I have read that wordpress uses MyISAM which doesn't actually build foreign key connections. While these tables may point to other tables already existing, in this example does declaring KEY order_id (order_id) create a variable of sorts called order_id that any other table can use to reference? Is this code specifically connecting one tables attributes to another tables attributes (it doesn't appear to be)? After these tables are built, I can inspect them in phpMyAdmin and see that there are indexes assigned but no foreign key constraints. How does this code create tables that point one table at another to build relations?
KEY `foo_bar` (`order_id`)
"KEY" is the same as "INDEX". It specifies that a separate data structure is maintained for the efficient access of the table via the column order_id.
foo_bar is the name of the index. It has no special meaning, and has very few uses. For example, DROP KEY foo_bar; is the way to get rid of the index.
In MyISAM, a "FOREIGN KEY" allowed, but ignored. In InnoDB, it does two things:
Create an index if one is not already provided
Provide a constraint. The default effectively "complain if the other table does not already have the value referenced".
Having an index is important for performance. The index above make this
SELECT ... WHERE order_id = 1234 ...
run in milliseconds, even if there are billions of rows in the table. Without the index, the query would take minutes or hours.
A PRIMARY KEY is a UNIQUE key, which is an INDEX.
UNIQUE(widget) says that only one row can have a particular value of `widget in the table.
PRIMARY KEY(id) says that each row is uniquely identified by the column id. InnoDB really wants each table to have a PK.
"id" is a convention (not a requirement) for the name of the PK. It is also INT AUTO_INCREMENT by convention. You may or may not actually ever touch id.
Tables can be related to each other in 3 main ways:
1:1 -- They share the same unique key. This is rarely useful; you may as well have a single table.
1:many -- An "order" has several "items" in it (one-order : many-items). This is usually handled by order_id being a column in the items table.
many:many -- students_classes -- each student is in many classes; each class has many students. This is implemented via a mapping table that has (usually) only two columns: student_id and class_id (no id is needed) and PRIMARY KEY(student_id, class_id) and INDEX(class_id, student_id). Those two indexes make it efficient to go from a known student to their classes, and vice versa.
Another convention for the PK of a table is to include the table name. (It is clutter to do that for other columns, such as order_status.) I was assuming this convention for student_id and class_id.
But now I am confused by your plugin_orders -- it has both id and order_id. If that table describes "orders", then I would expect order_id to be the PK instead of id.
And, if order_product is a list of all the "products" in each "order", then I would expect you to have the 1:many pattern.
What indexes to have?
PRIMARY KEY to uniquely identify each row -- either id or some column (or combination of columns) that are unique.
Other columns, as needed, for the SELECTs, UPDATEs, and DELETEs that you have. Do not blindly add indexes before having some clues of the queries that might need them.
Indexes sometimes help in sorting:
SELECT ... ORDER BY last_name, first_name;
together with
INDEX(last_name, first_name)
Indexes provide performance; FKs provide integrity checks. Neither is "required"; both are "desirable".
MyISAM is ancient; you should change to InnoDB.
Then do something like
SELECT ...
FROM plugin_orders AS o
JOIN plugin_order_product AS op
ON o.order_id = op.order_id
WHERE ...
In this example, the Optimizer will perform the query something like this:
Look at the WHERE to see which table is best filtered by the conditions there. Declare that to be the first table work with.
Scan through the first table, using an index if practical.
For each row in the first table, reach into the second table.
Reaching into the second table would probably be done via INDEX(order_id) on the second table. This would make the JOIN fast and efficient.
Both tables have INDEX(order_id), but that is not relevant.
Next example:
SELECT ...
FROM plugin_orders AS o
JOIN plugin_order_product AS op
ON o.order_id = op.order_id
WHERE o.people_id = 123 -- note
Pick o as the first table due to filtering on people_id
use op INDEX(people_id) to rapidly find the o rows that are relevant.
etc (op is the second table)
Next example:
SELECT ...
FROM plugin_orders AS o
JOIN plugin_order_product AS op
ON o.order_id = op.order_id
WHERE op.product_id = 9887 -- changed again
Pick op as the first table due to filtering on product_id
use o INDEX(people_id) to rapidly find the op rows that are relevant.
etc (o is the second table this time)
I'm using php and i have a table that have 2 column of varchar , one is used for user identification, and the other is used for page name entry.
they both must be varchar.
i want to insert ignore data when user enter a page to know if he visited it or not, and i want to fetch all the rows that the user have been in.
fetch all for first varchar column.
insert if not exist for both values.
I'm hoping to do it in the most efficient way.
what is the best way to insert without checking with another query if exist?
what is the best way other then:
SELECT * FROM table WHERE id = id
to fetch when the column needed is varchar?
You should consider a normalized table structure like this:
CREATE TABLE user (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE page (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE pages_visted (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user_id INT UNSIGNED,
page_id INT UNSIGNED,
UNIQUE KEY (user_id, page_id)
);
INSERT IGNORE INTO pages_visted (user_id, page_id) VALUES (:userId, :pageId);
SELECT page_id FROM pages_visted WHERE user_id = :userId;
I think you want to implement a composite primary key.
A composite primary key tells MySQL that you want your primary key to be a combination of fields.
More info here: Why use multiple columns as primary keys (composite primary key)
I don't know of a better option for your query, although I can advise, if possible:
Define columns to be NOT NULL. This gives you faster processing and requires less storage. It will also simplify queries sometimes because you don't need to check for NULL as a special case.
And with variable-length rows, you get more fragmentation in tables where you perform many deletes or updates due to the differing sizes of the records. You'll need to run OPTIMIZE TABLE periodically to maintain performance.
I am new to SQL and looking for some help. I have three tables: author, study and casestudy (which is a linking table). What I want to achieve is when data is inserted into author and study tables (from a web form) their Auto increment IDs get inserted into casestudy table if it is possible. I guess I will need to create triggers. AuthorId and StudyId in casestudy table is a composite key. Table structure is as follow:
CREATE TABLE `test`.`author` (
`AuthorId` INT(11) NOT NULL AUTO_INCREMENT,
`AuthorTitle` VARCHAR(45) NOT NULL,
PRIMARY KEY (`AuthorId`),
UNIQUE INDEX `AuthorId_UNIQUE` (`AuthorId` ASC));
CREATE TABLE `test`.`study` (
`StudyId` INT(11) NOT NULL AUTO_INCREMENT,
`Title` VARCHAR(45) NOT NULL,
PRIMARY KEY (`StudyId`),
UNIQUE INDEX `StudyId_UNIQUE` (`StudyId` ASC));
CREATE TABLE `test`.`casestudy` (
`AuthorId` INT(11) NOT NULL,
`StudyId` INT(11) NOT NULL,
PRIMARY KEY (`AuthorId`, `StudyId`),
INDEX `StudyId_idx` (`StudyId` ASC),
CONSTRAINT `AuthorId`
FOREIGN KEY (`AuthorId`)
REFERENCES `test`.`author` (`AuthorId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `StudyId`
FOREIGN KEY (`StudyId`)
REFERENCES `test`.`study` (`StudyId`)
ON DELETE NO ACTION
ON UPDATE NO ACTION);
Any advice will be appreciated. Thank you.
As far as I can see there is no data link between author and study tables. There is no such functionality as "one trigger on two tables update at a time". The best place to implement casestudy maintenance is in the procedure that populates the author and study tables during web form processing.
In PHP that can be done through collecting IDs after each Insert using mysql_insert_id(); (see Inserting data into multiple tables using php via a web form) and then using them all to update the linking table.
Using mysqli (and assuming $mysqli is the connection) that should be something like:
$AuthorTitle = $mysqli->real_escape_string($_POST[AuthorTitle value]);
$mysqli->query("INSERT INTO test.author(AuthorTitle) VALUES('$AuthorTitle')");
$AuthorId = $mysqli->insert_id;
$StudyTitle = $mysqli->real_escape_string($_POST[StudyTitle value]);
$mysqli->query("INSERT INTO test.study(Title) VALUES('$StudyTitle')");
$StudyId = $mysqli->insert_id;
$mysqli->query("INSERT INTO test.casestudy(AuthorId, StudyId) VALUES($AuthorId, $StudyId)");
Alternatively all three tables can be consistently populated through a stored procedure (or just an SQL script) that would take care of all the relevant web form fields in one go. Then after each Insert auto-generated ID can be collected using LAST_INSERT_ID(); (see LAST_INSERT_ID() MySQL).
$AuthorTitle = $mysqli->real_escape_string($_POST[AuthorTitle value]);
$StudyTitle = $mysqli->real_escape_string($_POST[StudyTitle value]);
$mysqli->multi_query("
START TRANSACTION;
INSERT INTO test.author(AuthorTitle) VALUES('$AuthorTitle');
SET #AuthorId = LAST_INSERT_ID();
INSERT INTO test.study(Title) VALUES('$StudyTitle');
SET #StudyId = LAST_INSERT_ID();
INSERT INTO test.casestudy(AuthorId, StudyId) VALUES(#AuthorId, #StudyId);
COMMIT;
");
Finally this scenario can be implemented through an Updatable and Insertable View across all three tables that would take care of storing the data in consistent manner.
how to limit the number of entry in inserting data in mysql database using php to 1
Any suggestions? Thanks .
You probably can't get it right in PHP since the trip back and forth to the database leaves room for another part of your application to create an entry. Normally we achieve this sort of thing by putting a unique index on the table that prevents duplication of data. For example:
CREATE TABLE alf_mimetype
(
id BIGINT NOT NULL AUTO_INCREMENT,
version BIGINT NOT NULL,
mimetype_str VARCHAR(100) NOT NULL,
PRIMARY KEY (id),
UNIQUE (mimetype_str)
) ENGINE=InnoDB;
If you attempt to insert a row with duplicate mimetype_str, the database will generate an exception. Catch it in your application and you'll know that your single entry for that particular row is already there.
You can create UNIQUE keys on multiple columns as well. Your primary key also represents a unique constraint and can consist of multiple columns.
I currently am working on some project that insert a lot of data into some tables. To ensure that my system is fast enough, I want to fragment my huge table into some smaller tables representing the months data. I have an idea of how it will work, but I still need some more informations.
The primary keys of my tables must be continuous so I thought of an architecture that would look like this:
CREATE TABLE `foo` (
`id` bigint(11) unsigned NOT NULL AUTO_INCREMENT,
}
CREATE TABLE `foo012014` (
`id` bigint(11),
`description` varchar(255),
}
CREATE TABLE `foo022014` (
`id` bigint(11),
`description` varchar(255),
}
On every insertion, the PHP page will look if a table already exists for the month and if not will create it.
The thing is, how do I get to bind the "foo" child table primary key to the "foo" mother table? Plus, is this design a bad practice or is it good?
It's not a good pratice, and difficult your queries.
With just the id you already have an index, which allows for better indexing of your data.
If your queries are also nicely written and organized, the time to execute a query in your database will be relatively small with 1 million rows or 20.
Solutions
First
For a better maintenance I recommend the following:
Add a new field in your table food: created datetime DEFAULT CURRENT_TIMESTAMP (works in MySQL 5.6+, for other versions, or set manually in every insert, or change to timestamp)
And, just use this field for group your data basead in datetime values, like that: 2014-01-24 13:18.
It's easy to select and manipulate.
Second
Create a external table with month and year, like that:
drop table if exists foo_periods;
create table foo_periods (
id int not null auto_increment primary key,
month smallint(4) not null,
year smallint(4) not null,
created datetime,
modified datetime,
active boolean not null default 1,
index foo_periods_month (month),
index foo_periods_year (year)
);
You can change smallint in month to varchar if you feels better.
Then, just create a FK, and done!
ALTER TABLE foo
ADD COLUMN foo_period_id int not null;
ALTER TABLE foo
ADD CONSTRAINT foo_foo_period_id
FOREIGN KEY (foo_period_id)
REFERENCES foo_periods (id);
References
If you want read more about fragmentation / optimization in MySQL, this is a great post.