Hi ok I have two tables one called Login and one called User there is a one to one relationship from the user table to the login table:
Login:
=-=-=-=-
LoginID (Primary, Not Null, Auto Inc)
UserID (Primary)
Username (not null)
Password (not null)
User:
=-=-=-=-
UserID (Primary)
Email
Name etc
I cant get my head around it but I dont know when it comes to coding it on my page how the UserID is set in the Login table related to the actual user?
If I take the client to the create user page and he fills in the user details then I forward him to the username and password fields which goes to a different table how is the UserID set in the Login Table? Atm its not?
Incase any one wants to reverse engineer my table data in mysql eer diagram see code below:
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL';
CREATE SCHEMA IF NOT EXISTS `gymwebsite` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci ;
USE `gymwebsite` ;
-- -----------------------------------------------------
-- Table `gymwebsite`.`User`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`User` (
`UserID` INT NOT NULL AUTO_INCREMENT ,
`Email` VARCHAR(245) NULL ,
`FirstName` VARCHAR(45) NULL ,
`SecondName` VARCHAR(45) NULL ,
`DOB` VARCHAR(15) NULL ,
`Location` VARCHAR(45) NULL ,
`Aboutme` VARCHAR(245) NULL ,
PRIMARY KEY (`UserID`) )
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`Pictures`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`Pictures` (
`PictureID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`PictureID`, `UserID`) ,
INDEX `fk_Pictures_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_Pictures_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`WallPostings`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`WallPostings` (
`UserwallID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`UserwallID`, `UserID`) ,
INDEX `fk_WallPostings_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_WallPostings_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`Login`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`Login` (
`LoginID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
`username` VARCHAR(245) NOT NULL ,
`password` VARCHAR(45) NOT NULL ,
PRIMARY KEY (`LoginID`, `UserID`) ,
INDEX `fk_Login_Userinfo` (`UserID` ASC) ,
CONSTRAINT `fk_Login_Userinfo`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`DietPlan`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`DietPlan` (
`DietPlanID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`DietPlanID`, `UserID`) ,
INDEX `fk_DietPlan_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_DietPlan_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`WorkoutPlan`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`WorkoutPlan` (
`WorkOutID` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`WorkOutID`, `UserID`) ,
INDEX `fk_WorkoutPlan_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_WorkoutPlan_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `gymwebsite`.`Friends`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `gymwebsite`.`Friends` (
`idFriends` INT NOT NULL AUTO_INCREMENT ,
`UserID` INT NOT NULL ,
PRIMARY KEY (`idFriends`, `UserID`) ,
INDEX `fk_Friends_Userinfo1` (`UserID` ASC) ,
CONSTRAINT `fk_Friends_Userinfo1`
FOREIGN KEY (`UserID` )
REFERENCES `gymwebsite`.`User` (`UserID` )
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
If User and Login has a 1:1 relation, you should drop LoginID from the Login table, and make UserID the primary key instead.
Or, if all users have login-information, you may consider moving the columns into the User table instead. (By doing so you also remove an entire class of problems related to enforcing 1-1 relations).
You should not insert any rows in the database until the user completes the entire registration form. Keep the form data in the session, and then at the end perform all inserts in all tables at once, then commit.
There is probably a function in c# to find out the last inserted id (UserID) to put in the Login table, otherwise have a look at the MySQL documentation for insert ID
Related
I have a very large CSV file I have to load on a regular basis that contains time series data. Examples of the headers are below:
| SiteName | Company | Date | ResponseTime | Clicks |
This data comes from a service external to the uploader. SiteName and Company are both string fields. In the database these are normalized. There is a Site table and a Company table:
CREATE TABLE [dbo].[Site] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Name] NVARCHAR(MAX) NOT NULL
)
CREATE TABLE [dbo].[Company] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[Name] NVARCHAR(MAX) NOT NULL
)
As well as the data table.
CREATE TABLE [dbo].[SiteStatistics] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[CompanyId] INT NOT NULL,
[SiteId] INT NOT NULL,
[DataTime] DATETIME NOT NULL,
CONSTRAINT [SiteStatisticsToSite_FK] FOREIGN KEY ([SiteId]) REFERENCES [Site]([Id]),
CONSTRAINT [SiteStatisticsToCompany_FK] FOREIGN KEY ([CompanyId]) REFERENCES [Company]([Id])
)
At around 2 million rows in the CSV file any sort of IO-bound iteration isn't going to work. I need this done in minutes, not days.
My initial thought is that I could pre-load Site and Company into DataTables. I already have the CSV loaded into a datatable in the format that matches the CSV columns. I need to now replace every SiteName with the Id field of Site and every Company with the Id field of Company. What is the quickest, most efficient way to handle this?
If you go with Pre-Loading the Sites and Company's you can get the distinct values using code:
DataView view = new DataView(table);
DataTable distinctCompanyValues = view.ToTable(true, "Company")
DataView view = new DataView(table);
DataTable distinctSiteValues = view.ToTable(true, "Site")
Then load those two DataTables into their SQL Tables using Sql-Bulk-Copy.
Next dump all the data in:
CREATE TABLE [dbo].[SiteStatistics] (
[Id] INT NOT NULL IDENTITY(1, 1) PRIMARY KEY,
[CompanyId] INT DEFAULT 0,
[SiteId] INT DEFAULT 0,
[Company] NVARCHAR(MAX) NOT NULL,
[Site] NVARCHAR(MAX) NOT NULL,
[DataTime] DATETIME NOT NULL
)
Then do an UPDATE to set the Referential Integrity fields:
UPDATE [SiteStatistics] ss SET
[CompanyId] = (SELECT Id FROM [Company] c Where ss.[Company] = c.Name),
[SiteId] = (SELECT Id FROM [Site] s Where ss.[Site] = s.Name)
Add the Foreign Key constraints:
ALTER TABLE [SiteStatistics] ADD CONSTRAINT [SiteStatisticsToSite_FK] FOREIGN KEY ([SiteId]) REFERENCES [Site]([Id])
ALTER TABLE [SiteStatistics] ADD CONSTRAINT [SiteStatisticsToCompany_FK] FOREIGN KEY ([CompanyId]) REFERENCES [Company]([Id])
Finally delete the Site & Company name fields from SiteStatistics:
ALTER TABLE [SiteStatistics] DROP COLUMN [Company];
ALTER TABLE [SiteStatistics] DROP COLUMN [Site];
I have made a table named "reservations" which contains a customer id and a house id. I made tables for houses and customers as well. I have made a datagrid, which contains the reservations data, but I also want it to contain the customers surname and the house code.
My tables are (in SQL Server Express):
CREATE TABLE [dbo].[houses]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Code] VARCHAR(50) NULL,
[Status] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[customers]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[Forename] VARCHAR(50) NULL,
[Surname] VARCHAR(50) NULL,
[Email] VARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
CREATE TABLE [dbo].[reservations]
(
[Id] INT IDENTITY (1, 1) NOT NULL,
[HouseId] INT NULL,
[CustomerId] INT NULL,
[StartDate] DATE NULL,
[EindDate] DATE NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_HouseId]
FOREIGN KEY ([HouseId]) REFERENCES [houses]([Id]),
CONSTRAINT [FK_CustomerId]
FOREIGN KEY ([CustomerId]) REFERENCES [customers]([Id])
);
I already created all the tables, but I don't know how to link them properly. I want to get the data and put it in a datagrid.
To select all data from Reservations, customers' Surname and house code, you need to run query:
Select R.*, C.Surname, H.Code
From [dbo].[reservations] R
inner join [dbo].[customers] C on C.Id = R.CustomerId
inner join [dbo].[houses] H on H.Id = R.HouseId
Try this:
select r.*,c.surname,h.code from reservation r,customers c,houses h where
r.customer_id=c.customer_id and r.house_id=h.house_id
I'm getting the following error when trying to insert values in the table:
INSERT statement conflicted with the FOREIGN KEY constraint "FK_BookingCustomer_Booking". The conflict occurred in database "C:\USERS\B00711882\SOURCE\WORKSPACES\SAILAWAY\SAILAWAY FINAL\SAILAWAYV2\SAILAWAYV2\APP_DATA\SAILAWAY.MDF", table "dbo.Booking", column 'ID'. The statement has been terminated.
My insert statement:
CREATE PROCEDURE [dbo].[inserBookingCustomer]
#customerID INT,
#bookingID INT
AS
INSERT INTO BookingCustomer (CustomerID, BookingID)
VALUES (#customerID, #bookingID)
RETURN 0
Table definitions:
Booking:
CREATE TABLE [dbo].[Booking]
(
[ID] INT IDENTITY (1, 1) NOT NULL,
[CharterID] INT NOT NULL,
[TotalCost] MONEY NOT NULL,
[StartDate] DATE NOT NULL,
[EndDate] DATE NOT NULL,
[TotalDays] INT NOT NULL,
CONSTRAINT [PK_Booking]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_Booking_CharterID]
FOREIGN KEY ([CharterID]) REFERENCES [dbo].[Charter] ([ID])
);
BookingCustomer (where information should be inserted):
CREATE TABLE [dbo].[BookingCustomer]
(
[ID] INT IDENTITY (1, 1) NOT NULL,
[BookingID] INT NOT NULL,
[CustomerID] INT NOT NULL,
CONSTRAINT [PK_BookingCustomer]
PRIMARY KEY CLUSTERED ([ID] ASC),
CONSTRAINT [FK_BookingCustomer_Booking]
FOREIGN KEY ([BookingID]) REFERENCES [dbo].[Booking] ([ID]),
CONSTRAINT [FK_BookingCustomer_Customer]
FOREIGN KEY ([CustomerID]) REFERENCES [dbo].[Customer] ([CustomerID])
);
This is an ASP.Net application.
Edit: My c# code: https://pastebin.com/5a8seRh4
That is because you was tried to insert a value that no are inserted before in the Booking table.
You need to insert the book first and next insert the reference of the book with the customer
I use MySql and I have 2 related tables.
The 'artikel' child table contains 3 rows each with an'idArtikel' of 1, 2 and 3.
And the 'artikelen' parent table has a row with idArtikel = 2.
If I change the idArtikel in that row to 3 (and Update()), I get an error, stating:
Update failed..exception Cannot delete or update a parent row: a
foreign key constraint fails (mydb.artikel, CONSTRAINT
fk_artikel_artikelen FOREIGN KEY (idArtikel) REFERENCES
artikelen (idArtikel) ON DELETE NO ACTION ON UPDATE NO ACTION)
All the keys are there, but i don't see the problem?!
HERE ARE THE 2 TABLE CREATION SQL scripts:
CREATE TABLE IF NOT EXISTS `mydb`.`artikelen` (
`idArtikelen` INT NOT NULL AUTO_INCREMENT,
`idKlanten` INT NOT NULL,
`idOmzetGroepen` INT NOT NULL,
`idArtikel` INT NOT NULL,
`Aantal` INT NULL,
`Omschrijving` VARCHAR(45) NULL,
`Datum` DATETIME NULL DEFAULT CURRENT_TIMESTAMP,
`StuksPrijsEx` DECIMAL(10,2) NULL,
`BtwPerc` INT NULL,
`Gefactureerd` TINYINT(1) NULL,
PRIMARY KEY (`idArtikelen`),
INDEX `idKlanten.idx` (`idKlanten` ASC),
INDEX `idArtikel.idx` (`idArtikel` ASC),
INDEX `idOmzetGroepen.idx` (`idOmzetGroepen` ASC),
INDEX `idArtikelen.idx` (`idArtikelen` ASC),
CONSTRAINT `fk_artikelen_klanten1`
FOREIGN KEY (`idKlanten`)
REFERENCES `mydb`.`klanten` (`idKlanten`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `mydb`.`artikel` (
`idArtikel` INT NOT NULL AUTO_INCREMENT,
`Omschrijving` VARCHAR(35) NULL,
`Merk` VARCHAR(20) NULL,
`Type` VARCHAR(15) NULL,
`StuksPrijsEx` DECIMAL(10,2) NULL,
`idOmzetGroepen` INT NOT NULL,
`BtwPerc` INT NULL DEFAULT 21,
INDEX `idOmzetGroepen.idx` (`idOmzetGroepen` ASC),
INDEX `idArtikel.idx` (`idArtikel` ASC),
CONSTRAINT `fk_artikel_artikelen`
FOREIGN KEY (`idArtikel`)
REFERENCES `mydb`.`artikelen` (`idArtikel`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
ENGINE = InnoDB
#
Any help, is appreciated a lot!
Thanks in advance for any input.
Ron.
The error I get is this "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_vacation_users". The conflict occurred in database "TestAtt", table "dbo.users", column 'userID'."
I'm trying to insert into users with this:
INSERT into users (firstName, lastName, userName, password, team, fingerID, type, isActive) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}')",
firstNameAddBox.Text, lastNameAddBox.Text, userNameAddBox.Text, passwordAddBox.Text,
teamAddUserCombo.Text, fingerIdAddBox.Text, userTypeAddCombo.SelectedValue, isActiveCheck.Checked);
My users table looks like this:
CREATE TABLE
users
(
userID INT NOT NULL IDENTITY,
userName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
password NVARCHAR(100) COLLATE Romanian_CI_AS NOT NULL,
firstName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
lastName NVARCHAR(50) COLLATE Romanian_CI_AS NOT NULL,
team TINYINT NOT NULL,
type TINYINT NOT NULL,
fingerID SMALLINT NOT NULL,
isActive BIT DEFAULT 1 NOT NULL,
CONSTRAINT PK_users PRIMARY KEY (userID),
CONSTRAINT FK_users_userType FOREIGN KEY (type) REFERENCES userType (typeID),
CONSTRAINT users_idx UNIQUE (fingerID)
);
The vacation table looks like this:
CREATE TABLE
vacation
(
ID INT NOT NULL IDENTITY,
userID INT NOT NULL,
vacation TINYINT DEFAULT 0 NOT NULL,
extraDays TINYINT DEFAULT 0 NOT NULL,
PRIMARY KEY (ID),
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
);
And this is the trigger:
ALTER TRIGGER "dbo"."newUserTrigger"
on "dbo"."users"
AFTER INSERT
as
begin
DECLARE #newUserID int
SELECT #newUserID = (SELECT userID FROM Inserted)
INSERT INTO vacation (userID) VALUES (#newUserID)
end;
So if I disable the trigger the insert works but with the trigger on it seems it wont insert the userID in the vacation table also.
I think your foreign key is incorrect, the column that's referencing users is userID, not ID:
CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (userID)
But your trigger is also broken because inserted can contain multiple (or no) rows. So it should be:
ALTER TRIGGER "dbo"."newUserTrigger"
on "dbo"."users"
AFTER INSERT
as
begin
INSERT INTO vacation (userID) SELECT userID from Inserted
end;
Here's the problem:
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
This is saying that the ID column in vacation must have a matching value in userId in users. I think (ID) should be (userID). It should work OK then.
CONSTRAINT FK_vacation_users FOREIGN KEY (ID) REFERENCES users (userID)
should be
CONSTRAINT FK_vacation_users FOREIGN KEY (userID) REFERENCES users (ID)