SQL Can't create Foreign key - sql

I'm sure my question would be kinda silly, but I can't solve it. Here is my issue:
create table Product
(
ProductID int PRIMARY KEY,
ProductName varchar(16),
RetrailPrice int,
WholesalePrice int,
MonthDelivery int,
Waste int,
StorageName varchar(16)
)
create table Storage
(
StorageID int PRIMARY KEY,
StorageName varchar(16),
City varchar(16),
Employees int,
Area int,
ProductID int
)
And of course I want to link them
alter table Product
add FOREIGN KEY (StorageName) references Storage(StorageName)
But I can't do it, I'm wrong somewhere :/

You have to reference the PK from the Storage table. StorageName is a poor choice for a FK. What if there are Storages with the same name in different cities?
Replace the StorageName in the Product table with StorageID
create table Product(
ProductID int PRIMARY KEY,
ProductName varchar(16),
RetrailPrice int,
WholesalePrice int,
MonthDelivery int,
Waste int,
StorageID int) --this has chnaged, it will hold the id/PK of the Storage
create table Storage(
StorageID int PRIMARY KEY,
StorageName varchar(16),
City varchar(16),
Employees int,
Area int,
ProductID int)
And then:
alter table Product
add FOREIGN KEY (StorageID) references Storage(StorageID)

Related

How to impelment a foriegn key in sql?

I tried writing it like that but i keep getting errors but when i removed the line it worked how do i set a foreign key in this?
PlayerNum int,
PlayerName varchar(255),
PlayerPosition varchar(255),
NumOfRedCards int,
NumOfYellowCards int,
Goals int,
Fouls int,
PRIMARY KEY (PlayerNum),
/*FOREIGN KEY (TeamName) REFERENCES Teams(TeamName)*/
);```
You don't have a column defined for TeamName in your table. Try this:
PlayerNum int,
PlayerName varchar(255),
PlayerPosition varchar(255),
NumOfRedCards int,
NumOfYellowCards int,
Goals int,
Fouls int,
TeamName varchar(255),
PRIMARY KEY (PlayerNum),
FOREIGN KEY (TeamName) REFERENCES Teams(TeamName)
);```
That should work, assuming that you have a Teams table with a defined primary key of TeamName.
NOTE: I would highly recommend NOT having a varchar for a primary key. A far better implementation would be:
PlayerNum int,
PlayerName varchar(255),
PlayerPosition varchar(255),
NumOfRedCards int,
NumOfYellowCards int,
Goals int,
Fouls int,
TeamId int,
PRIMARY KEY (PlayerNum),
FOREIGN KEY (TeamId) REFERENCES Teams(TeamId)
);```
You can always join tables on the ID to get the team name, or at worst write a view for a flattened structure to query against.
SELECT p.PlayerNum, p.PlayerName, ..., t.TeamName FROM Players p
LEFT JOIN Teams t ON p.TeamId = t.TeamId
WHERE p.PlayerId = 1

unable to create primary key on phpmyadmin sql

this is my code
CREATE TABLE orders(
id integer NOT NULL,
name varchar(12),
orderno int,
city varchar(12),
price int
PRIMARY KEY ('id')
);
please check this image for error
try this
CREATE TABLE orders(
id int NOT NULL PRIMARY KEY,
name varchar(12),
orderno int,
city varchar(12),
price int
);
While Creating Table you can Declare the primary key Attribute with the type of the attribute. like.
CREATE TABLE orders(
id integer PRIMARY KEY NOT NULL,
name varchar(12),
orderno int,
city varchar(12),
price int);

SQL Server 2012 creating tables and values

For some odd reason I can't create a table and because if that I can't insert any values into those tables. This is a new database and I am having a bit of a brain fart.. any help??? thanks
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(25) FOREIGN KEY (Agencies)
)
Example of a working code
create table Agencies
(
AgencyID nvarchar(20) primary key,
AgName nvarchar(40),
AgAddress nvarchar(40),
AgPhone int
)
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(20) FOREIGN KEY REFERENCES Agencies(AgencyID)
)
Hope it helps!
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(25) FOREIGN KEY REFERENCES Agencies(Your_Agencies_ID_COLUMN)
)
There two ways of creating foreign key constrain:
creating a foreign key constraint within the table definition
CREATE TABLE [dbo].[DataSource]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Pts] TINYINT
,[PtsOf] TINYINT
, CONSTRAINT [PK_DataSource] PRIMARY KEY ([SurveyInstanceID], [ProtoQuestionID])
);
CREATE TABLE [dbo].[DataSourceComments]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Comments] NVARCHAR(MAX)
,CONSTRAINT [FK_DataSourceComments_DataSource_SurveyInstanceID_ProtoQuestionID]
FOREIGN KEY ([SurveyInstanceID], [ProtoQuestionID])
REFERENCES [dbo].[DataSource] ([SurveyInstanceID], [ProtoQuestionID])
);
creating a foreign key constraint for existing table
CREATE TABLE [dbo].[DataSource]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Pts] TINYINT
,[PtsOf] TINYINT
,CONSTRAINT [PK_DataSource] PRIMARY KEY ([SurveyInstanceID], [ProtoQuestionID] )
);
CREATE TABLE [dbo].[DataSourceComments]
(
[SurveyInstanceID] BIGINT
,[ProtoQuestionID] INT
,[Comments] NVARCHAR(MAX)
);
ALTER TABLE [dbo].[DataSourceComments]
ADD CONSTRAINT [FK_DataSourceComments_DataSource_SurveyInstanceID_ProtoQuestionID]
FOREIGN KEY ([SurveyInstanceID], [ProtoQuestionID])
REFERENCES [dbo].[DataSource] ([SurveyInstanceID], [ProtoQuestionID]);
Note, that in both cases I am specifying the FK constraint name. It's is a recommended to have some naming convention which to apply to all new FK.
I believe your foreign key is incorrect... maybe try this?
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID NVARCHAR(25) FOREIGN KEY REFERENCES Agencies(AgencyID)
)
Supposing "AgencyID" is the ID in your Agencies Table.
Try the below code
CREATE TABLE Agency
(
AgencyID INT PRIMARY KEY IDENTITY,
Name NVARCHAR(20)
)
CREATE TABLE Customers
(
CustomerID INT PRIMARY KEY IDENTITY,
CustomerFName NVARCHAR(20),
CustomerLName NVARCHAR(25),
DateOfTravel DATETIME,
TravelLocation NVARCHAR(25),
AgencyID INT FOREIGN KEY REFERENCES Agency(AgencyID)
)
First you have to create the parent table ie, Agency table. Then create the child (Customers) and refer the parent.

Database design with creating a product that has two prices

I'm creating a database design for our water refilling system and I'm just new to databases. I am stuck with creating table that provides two different prices for a product. To further explain my problem, here's an example, a product's ('5 GALLON') price changes when it is delivered or bought on point by a customer. For example a delivered ('5 GALLON') is 45 pesos while a bought on point gallon is only 40 pesos. Can someone help me please?
Here's my codes so far
create table Product (
product_id int primary key,
prodtype_id int,
product_name varchar(55),
product_quantity int
)
-----NOT SURE IF THESE TWO TABLES ARE CORRECT
create table DeliveryPrice (
prod_id int,
product_price money,
foreign key (prod_id) references Product
)
create table OnPointPrice(
prod_id int,
product_price money,
foreign key (prod_id) references Product
)
You're likely better off just having the two prices in the Product table. They are attributes of the product, so that's where they belong.
Also, you should specify which columns are NOT NULL in your database (which should be most of them).
So is this correct?
create table Product(
product_id int primary key,
product_name varchar(55) not null,
product_quantity int not null,
pickup_price money not null,
delivery_price money not null
)
create table Customer(
customer_id int primary key,
customer_name varchar (255) not null,
customer_address varchar(200),
customer_phone int
)
create table INVOICE(
inv_number int primary key,
customer_id varchar(5),
foreign key (customer_id) references Customer,
inv_date date not null,
bought_mode char(10) not null
)
create table LINE(
INV_NUMBER int,
foreign key (INV_NUMBER) references INVOICE,
LINE_NUMBER INT not null,
PRIMARY KEY (INV_NUMBER, LINE_NUMBER),
line_quantity int not null,
line_price money not null
)

Sql query join and aggragation at the same time

How can I Select the Sum of the ProjectPossibilityRatio column from the ProjectCompletion table given the ProjectID? I couldnt find sum:
SELECT pp.ProjectID,
pp.ProjectAlias,
Sum(pd.projectpossibilityratio)
FROM project pp
INNER JOIN projectcompletion pc
ON pp.projectId = pc.projectID
JOIN projectprocedure pd
ON pd.projectprocedureID = pc.projectprocedureID
GROUP BY pd.projectpossibilityratio
Here are the table definitions:
Create TABLE ProjectType(
ProjectTypeID int identity(1,1),
ProjectTypeName nvarchar(100),
Description nvarchar(200),
primary key(ProjectTypeID)
)
CREATE TABLE Project(
ProjectID int identity(1,1),
ProjectAlias nvarchar(100),
ProjectTypeID int foreign key references ProjectType(ProjectTypeID),
MandatedCompanyID int foreign key references Company(CompanyID),
Iscurrent bit,
BuySide bit,
TeamID int foreign key references WorkTeam(TeamID),
ProjectTurnOver varchar(100),
ProjectStartDate Datetime
primary key(ProjectID))
CREATE TABLE ProjectProcedure(
ProjectProcedureID int identity(1,1),
ProjectProcedureName nvarchar(100),
ProjectProcedureDescription nvarchar(200),
ProjectType int foreign key references ProjectType(ProjectTypeID),
ProjectProcedurePosition int,
ProjectProcedureTime smallint,
ProjectPossibilityRatio int,
Primary Key(ProjectProcedureID))
CREATE TABLE ProjectCompletion(
ProjectID int foreign key references Project(ProjectID),
ProjectProcedureID int foreign key references ProjectProcedure(ProjectProcedureID),
StartDate Datetime,
IsCompletedDate Datetime
Primary Key(ProjectID,ProjectProcedureID)
)
Add all the column names that you are selecting to the group by list.
Try this:
SELECT pp.ProjectID,pp.ProjectAlias,Sum(pd.projectpossibilityratio)
FROM project pp INNER JOIN projectcompletion pc ON pp.projectId=pc.projectID
JOIN projectprocedure pd ON pd.projectprocedureID=pc.projectprocedureID
GROUP BY pp.ProjectID,pp.ProjectAlias
And I agree with LeftyX, you should go back and accept answers