using INSERT IGNORE across two columns - mysql

Im looking to use INSERT IGNORE so that I avoid entering duplicate fields into my database but i want to check this across 2 columns not 1.
So only if columns DateandTime AND Horse don't exists together in the same row

You shoud work with indices.
If you want to check that the values for DateandTime and Horse are both not set, give each a unique index.
If you want to check it the combinaiton of both doesn't exist jet, give them a combined index that is set to unique.
I recommend to use phpmyadmin. You can set indices in the Structure tab of a table.
There is no php needed to achive this.
Tt you Comment about a combined index:
ALTER TABLE Race_Records ADD UNIQUE INDEX unique_index ( `Horse`, `DateandTime` ) ;
the unique_index is the name of the index. You can choose that yourself, it you warn.
All Arguments in the () are used as the cols, that are added to that index.
And you need to set the UNIQUE to make it an unique index. Otherwise it will only be a normal index that only helps with searching.

Related

use Foreign key indexes in multi index mysql

I have A table with almost 20 fields which several of those are Foreign Key that already has been indexed by Mysql, now I want to create a multi-indexes index that it contains 3 FK field,
First tried was based on Fields
ALTER TABLE `Add`
Add INDEX `IX_Add_ON_IDCat_IDStatus_IDModeration_DateTo_DateAdded`
(`IDCategory`,`IDStatus`,`IDModeration`,`DateTo`,`DateAdded`);
But I think it's better to have an index on indexes instead of fields but my following effort faced with error: Error Code: 1072. Key column 'FK_Add_Category' doesn't exist in table
ALTER TABLE `Add`
Add INDEX `IX_Add_ON_IDCat_IDStatus_IDModeration_DateTo_DateAdded`
(`FK_Add_Category`,`FK_Add_AddStatus`,`FK_Add_AddModeration`,
`IX_Add_DateTo`,`IX_Add_DateAdded`);
My question is is it possible to add an index on exists Indexes ( FK index in my case ) or not and there is the only way to create an index on Columns? if yes How I create that?
An index is an ordered list of values. It is used to make it more efficient to find rows in the table.
Think about the common, real-life, example of INDEX(last_name, first_name). It makes it easy to look up someone if you have their last name and first name. And sort of easy if you have only their last name.
But it is useless if all you have is their first name.
FOREIGN KEYs necessitate a lookup. Apparently you have a FK to AddStatus, since I see FK_Add_AddStatus. That FK generated a lookup for AddStatus. Think of that as being like a separate index on first_name. It is totally separate from the index on last_name & first_name.
5 columns is usually too many to put into a single index.
MySQL uses only one index for a given SELECT.
So, now, I ask, what SELECT might use that 5-column index? Please show us it. We can discuss whether it is useful, and whether the columns are in the optimal order.

Fastest way to retrieve records from multiple tables

I need to retrieve columns from two tables and I have used an INNER JOIN. But its consuming lot of time during loading the page. Is there any better and faster way to achieve the same?
Select P.Col1, P.Col2, P.Col3, P.Col4, P.Col5, C.Col1, C.Col2, C.Col3 from Pyalers P inner join Customers C on C.Col1 = P.Col1 where P.Col2 = 5
Thanks in Advance.
Without knowing your DDL, there's no way to say.
But conceptually this is ok, just be sure you have proper indexs sets.
For instance: (is your table name really 'Pyalers'? Assuming 'players')
CREATE INDEX idx_players ON `players` (col1);
CREATE INDEX idx_customers ON `customers` (col1);
use the columns you need for joinning the 2 tables.
http://dev.mysql.com/doc/refman/5.0/en/create-index.html
You're doing it the right way, but if you don't have indexes on your tables on the correct columns, it's not going to be very fast for tables of any size. Do Pyalers.col1 and Customers.col1 both have indexes on them?
Show us how the tables are defined.
Be sure your table has the needed indexes... as a "thumb rule", every field which is used for search (WHERE) or data joins (INNER JOIN, LEFT JOIN, RIGHT JOIN) should be indexed.
Example: If you are creating a table, you can add your indexes at that time (notice that your tables should always have a primary key):
CREATE TABLE myTable (
myId int unsigned not null,
someField varchar(50),
primary key (myId),
index someIdx(someField)
);
If your table already exists, and you want to add indexes, you need to use the ALTER statement:
ALTER TABLE myTable
ADD INDEX someIdx(someField),
ADD PRIMARY KEY (myId);
Rules:
To define an index you most provide a unique name for it, and specify the fields included in the index: INDEX myIndex(field1, field2, ...)
There are different types of indexes: PRIMARY KEY is used for primary keys (that's obvious, huh?); INDEX is an 'ordinary index', just used to speed up search and join operations; UNIQUE INDEX is an index that prevents duplicate values.
Recomendations:
Whenever you can, index all numeric and date fields that are relevant (ids, birth date, etc.). Avoid creating indexes on fields that contain 'double' values.
Don't abuse of indexes, because abuse can create very large index files.
Tips:
If you want to see how your query will be executed, you can use the EXPLAIN statement:
EXPLAIN SELECT a., b. FROM a INNER JOIN b on a.myId = b.otherId
This instruction will show you the execution plan of the query. If in the last column you see 'file sort' or 'using temporary', you may (just may) need aditional indexes (notice that if you use GROUP BY you will almost always get the 'using temporary' message)
Hope this help you

UNIQUE Constraint, only when a field contains a specific value

I'm trying to create a UNIQUE INDEX constraint for two columns, but only when another column contains the value 1. For example, column_1 and column_2 should be UNIQUE only when active = 1. Any rows that contain active = 0 can share values for column_1 and column_2 with another row, regardless of what the other row's value for active is. But rows where active = 1 cannot share values of column_1 or column_2 with another row that has active = 1.
What I mean by "share" is two rows having the same value(s) in the same column(s). Example: row1.a = row2.a AND row1.b = row2.b. Values would be shared only if both columns in row1 matched the other two columns in row2.
I hope I made myself clear. :\
You can try to make multi-column UNIQUE index with column_1, column_2 and active, and then set active=NULL for the rows where uniqueness not required. Alternatively, you can use triggers (see MySQL trigger syntax)
and check for each inserted/updated row if such values are already in the table - but I think it would be rather slow.
I'm trying to create a UNIQUE INDEX constraint for two columns, but only when another column contains the value 1
You can set the value of "another column" to a unique value that does not equal to 1. for example the id of a record.
Then the unique index constraint could be applied to all three columns including the "another column". Let's call the "another column" columnX.
Set the value of columnX to 1 if you want to apply the unique constraint to a record. Set the value of columnX to a unique value if you don't want to apply the unique constraint.
Then no extra work/triggers needed. The unique index to all three columns could solve your problem.
I am not sure about MySQL syntax, but it should have pretty much the same thing that SQL Server has:
CREATE UNIQUE INDEX [UNQ_Column1Column2OnActive_MyTable]
ON dbo.[MyTable]([column1,column2)
WHERE ([active] = 1);
This index will make sure if active=1 then column1 and column2 combination is unique across the table.
In SQL Server this could be accomplished with check constraints, however I do not know if MySQL supports anything similar.
What will work on any database, is that you can split the table in two. If the records where active =0 are just history records, and will never become active again, you could just move them to another table, and set a simple unique constraint on the original table.
I am not sure I understand you 100% but lets say you have a table that has a status column and you want to make sure there is only one raw with a status of 'A' (Active). You are OK with many rows with statuses of 'I' or 'Z' or anything else. Only one row is allowed with status of 'A'.
This will do the trick.
CREATE UNIQUE INDEX [Idx_EvalHeaderOnlyOneActive]
ON [dbo].[EvalHeader]([Hdr Status])
WHERE [Hdr Status] = 'A';
indexes are agnostic of external influences. This kind of constraint would have to be implemented outside your database.

MySQL multiple index types?

I've noticed that in PHPMyAdmin I can individually index columns or I can use checkboxes to select fields and then click index and they're indexed in a different way. Does this mean that if for a given table I have 2 columns of that table that define each row as unique (instead of just a simple single column id`) I should index those together to increase performance?
A multiple-column index can be considered a sorted array containing values that are created by concatenating the values of the indexed columns.
MySQL uses multiple-column indexes in such a way that queries are fast when you specify a known quantity for the first column of the index in a WHERE clause, even if you do not specify values for the other columns.
If you have two columns named last_name and first_name and you create an index INDEX name (last_name,first_name), The index can be used for queries that specify values in a known range for last_name, or for both last_name and first_name.
Source: http://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html
So, it may not be helpful in your particular case. Becuase if you want to query on the later columns (for example: SELECT * FROM test WHERE first_name='Michael' or SELECT * FROM test WHERE last_name='Widenius' OR first_name='Michael), the index will not be used and the queries will be slower.

phpMyAdmin wants to add multiple indices as one multi-column index

I'm creating tables using phpMyAdmin and want to define two different columns as indices. I'm not trying to create a multi-column index but phpMyAdmin creates them as such. Are there any possible issues with that? The fields don't relate to each other directly and both fields will not be used in WHERE clauses simultaneously.
Consider:
ALTER TABLE `documents` ADD INDEX (`offer_number`, `contract_number`);
And:
ALTER TABLE `documents` ADD INDEX (`offer_number`);
ALTER TABLE `documents` ADD INDEX (`contract_number`);
What's the difference?
MySQL can only make use of an index if the first column(s) of the index match the columns used in the query. In other words, if you perform a query where an index on contract_number could be used, the composite index won't be used since contract_number is not the first column in that key. The composite index could be used for a query where offer_number is used, however.
http://dev.mysql.com/doc/refman/5.0/en/multiple-column-indexes.html
http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html
Given what you say about these fields, they should not be a part of one multi column index.
If you want to create single column indexes on PhpMyAdmin, you need to create them one at a time.