how to find primary key for table in mysql - mysql

I have a given table in MySQL called inventory.. all the descriptions in table null = 'Yes' and default = 'Null'. the field names in the table are inventory, items, sales and Staff.
in inventory table I have part_no, decript,on_hand,location,unitcost, discontinue..
is it correct in stating that part_no would be my primary key as this this record can not have a duplicate value.
thank you for confirming or correcting my assumption.. Is there a query that would validate this.

did you already create your table? and could find the primary key? primary key ensure unique row and restrict duplicate value. if you want to find primary key of a table use.
SHOW KEYS FROM tablename WHERE Key_name = 'PRIMARY'

The below query gets the part_no and it's number of appearances, if you see 2 or above, then part_no can't be your primary key, and you have to select another or more primary keys. Make sure part_no IS NOT NULL !!! as you can't have null primary keys
select part_no, count(*) as appearances
from inventory
group by part_no
if you want to know it faster because of many rows, you run this
select max(appearances)
from ( select part_no, count(*) as appearances
from inventory
group by part_no )
if max is 1 you are ok. If not, add to group by and select another collumn and do the same. Then you can determine what collumn/s is/are your primary key. And with alter table, or some GUI you can change it.

Related

is it possible to not give a primary key to an association table?

Hi I'm using phpmyadmin to create a database to control order made from a companyA to other companies. I created two kind of object that the company can order and that needs to be distinguished:
Accessories (it can be batteries made by the enterprise using there InventoryItems, or bought from another enterprise)
InventoryItems (it can be screws or nails bought from another enterprise)
so here's what I got in my deliver table
CREATE TABLE `deliver` (
`AccesoryId` int(36) NOT NULL,
`ItemId` int(36) NOT NULL,
`OrderId` int(36) NOT NULL,
`quantity` int(11) NOT NULL
)
everything looks great but here are my issues:
I can't make an order that doesn't contain only accessories or only items.they can't be NULL because they are part of the primarykey
so I tried to remove them from the primary key and only using the orderId but now:
I can't link different Items or Accessories to one order.because it would duplicate the primary key
so I tried to remove the composite primary key to get rid of those issues and to create a relation that would link the primary keys of each table (this would help me be able to link the objects to the order and at the same time let me make them NULL)
now my question is, is it that bad that an association table don't have any primary key or is there a better way to do this ?
A table doesn't have to have a primary key. So generally it's okay for the deliver table not to have one. What it needs, though, to guarantee consistency:
Foreign key constraints of course.
A check constraint that in every row exactly one of accessory_id and item_id is null and the other not null.
A unique index on (order_id, accessory_id)
A unique index on (order_id, item_id)
I'd probably use two deliver tables instead:
order_item (order_id, item_id, quantity)
order_accessory (order_id, accessory_id, quantity)
Then both would have a primary key (because item_id resp. accessory_id is not null) and its easier to query the data.

multiple primary key defined [duplicate]

Here is a gross oversimplification of an intense setup I am working with. table_1 and table_2 both have auto-increment surrogate primary keys as the ID. info is a table that contains information about both table_1 and table_2.
table_1 (id, field)
table_2 (id, field, field)
info ( ???, field)
I am trying to decided if I should make the primary key of info a composite of the IDs from table_1 and table_2. If I were to do this, which of these makes most sense?
( in this example I am combining ID 11209 with ID 437 )
INT(9) 11209437 (i can imagine why this is bad)
VARCHAR (10) 11209-437
DECIMAL (10,4) 11209.437
Or something else?
Would this be fine to use this as the Primary Key on a MYSQL MYISAM DB?
I would use a composite (multi-column) key.
CREATE TABLE INFO (
t1ID INT,
t2ID INT,
PRIMARY KEY (t1ID, t2ID)
)
This way you can have t1ID and t2ID as foreign keys pointing to their respective tables as well.
I would not make the primary key of the "info" table a composite of the two values from other tables.
Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?
I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.
the syntax is CONSTRAINT constraint_name PRIMARY KEY(col1,col2,col3) for example ::
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
the above example will work if you are writting it while you are creating the table for example ::
CREATE TABLE person (
P_Id int ,
............,
............,
CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)
);
to add this constraint to an existing table you need to follow the following syntax
ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY (P_Id,LastName)
Suppose you have already created a table now you can use this query to make composite primary key
alter table employee add primary key(emp_id,emp_name);
Aside from personal design preferences, there are cases where one wants to make use of composite primary keys. Tables may have two or more fields that provide a unique combination, and not necessarily by way of foreign keys.
As an example, each US state has a set of unique Congressional districts. While many states may individually have a CD-5, there will never be more than one CD-5 in any of the 50 states, and vice versa. Therefore, creating an autonumber field for Massachusetts CD-5 would be redundant.
If the database drives a dynamic web page, writing code to query on a two-field combination could be much simpler than extracting/resubmitting an autonumbered key.
So while I'm not answering the original question, I certainly appreciate Adam's direct answer.
Composite primary keys are what you want where you want to create a many to many relationship with a fact table. For example, you might have a holiday rental package that includes a number of properties in it. On the other hand, the property could also be available as a part of a number of rental packages, either on its own or with other properties. In this scenario, you establish the relationship between the property and the rental package with a property/package fact table. The association between a property and a package will be unique, you will only ever join using property_id with the property table and/or package_id with the package table. Each relationship is unique and an auto_increment key is redundant as it won't feature in any other table. Hence defining the composite key is the answer.
CREATE TABLE `mom`.`sec_subsection` (
`idsec_sub` INT(11) NOT NULL ,
`idSubSections` INT(11) NOT NULL ,
PRIMARY KEY (`idsec_sub`, `idSubSections`)
);
#AlexCuse I wanted to add this as comment to your answer but gave up after making multiple failed attempt to add newlines in comments.
That said, t1ID is unique in table_1 but that doesn't makes it unique in INFO table as well.
For example:
Table_1 has:
Id Field
1 A
2 B
Table_2 has:
Id Field
1 X
2 Y
INFO then can have:
t1ID t2ID field
1 1 some
1 2 data
2 1 in-each
2 2 row
So in INFO table to uniquely identify a row you need both t1ID and t2ID

Duplicate Key Error in phpAdmin

I am using PHPAdmin to create a unique index on a field. It comes back with Error 1062 - Duplicate Key on . . . then it gives me the offending data. The issue is the data is NOT a duplicate. Each record has a unique entry in that field. Thinking it was an anomaly, I deleted that entry and tried again. It gave me the same error this time on the last row before the deleted record.
Table schema:
CREATE TABLE prospects (
client_id int(11) NOT NULL AUTO_INCREMENT,
company varchar(64) DEFAULT NULL,
created_on timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
... some other fields like first_name...
PRIMARY KEY (client_id),
KEY first_name (first_name,last_name)
) ENGINE=MyISAM AUTO_INCREMENT=1958 DEFAULT CHARSET=latin1
Alter table statement failing:
ALTER TABLE acceler6_accelrefer.prospects ADD UNIQUE company_ui (company);
Any help or insight would be appreciated.
As much as you don't want to hear it again from the comments, you've got a duplicate company name. Note, this does not mean the entire record is a duplicate, but when you add a unique on company, every record has to have a unique company. I'm going to guess you've sometimes got more than one prospect entry per company.
To verify, try this:
SELECT count(company), count(distinct company) FROM prospects;
If these number are identical, then ok, you win, you've not got more than one record with the same company, but I'm certain they'll be different.
To find out exactly which ones are duplications you can do this:
SELECT company, count(company) AS counter
FROM prospects
GROUP BY company
HAVING counter > 1;
If you just want fast lookup of the client_id's by company, drop the UNIQUE and just use a regular key.
ALTER TABLE acceler6_accelrefer.prospects ADD KEY company_ui (company);

Mysql Help Needed

I have a table named group Info. It has three fields namely id,user_id, and group_id.
My question is how to assign unique users to a group i-e same user may not be repeated in a same group.
Table structure for group Info is as follows;
id int(11) Auto increment,Primary key NOT NULL,
user_id int(11) Not Null,
group_id int(11) Not Null
I have made the user_id unique.But there are two groups(2 group_id(1 and 2)).Selecting users for groupB gives error duplicate entry.
user_id = 1,2,3,4,5,6,7,8;
group_id= 1,2;
Kindly help me how to solve this.Iam not good in english so apologies for my language.
ALTER TABLE `tbl_name` ADD UNIQUE (
`col1` ,
`col2`
);
Change col1 with user_id and col2 with group_id and tbl_name with your table name.
If user_id is unique, then you probably shouldn't be creating a join table: just add a group pointer to the user table.
If, on the other hand, a user can belong to more than one group, then your current design is probably appropriate, but you shouldn't make user_id unique (although you might want to make a unique composite key on the combination of user_id and group_id).

MySQL View where foreign key can be NULL

I would like to know how to create view which also works even if the foreign key is NULL. For example we have table Person which has a primary key and two foreign keys:
IdPerson
FkName
FkSurname
Both foreign keys can be NULL. Now we also have two tables, table Name:
IdName
Name
And table Surname:
IdSurname
Surname
Now we create view to display name and surname for each Person:
CREATE VIEW `Database`.`ViewPerson` AS
SELECT `N`.`Name`, `S`.`Surname`
FROM `Person` `P`, `Name` `N`, `Surname` `S`
WHERE (`P`.`FkName` = `N`.`IdName`) AND (`P`.`FkSurname` = `S`.`IdSurname`)
The problem is, if the foreign key FkSurname is NULL, than that row will not be displayed even though FkName is defined. I want that even if both foreign keys are NULL it still returns row where both columns are NULL. Now I know that I could solve it by adding in table Name and in table Surname row, that has NULL under Name/Surname and then in the FkName and FkSurname reference a row that has NULL values under those two columns. But I would still like to find out if there is a solution where foreign key is NULL and the row is returned.
If I understand your question correctly, you want to get the corresponding values (even if null) for the Name and Surname fields in the Name and Surname table for each record in the Person table.
This seems like a straightforward case where LEFT JOIN would work correctly. So, based on your query above, the SQL would be:
CREATE VIEW Database.ViewPerson AS
SELECT
N.Name, S.Surname
FROM Person P
LEFT JOIN Name N ON N.IdName = P.FkName
LEFT JOIN Surname S ON N.IdSurname = S.FkSurname;
(sorry of the syntax isn't 100% correct, I didn't go through and create a test table to confirm it)