Logical Modeling difficulty - sql

I have a task to design a simple database that will store information about restaurants, customers and Categories that each restorant falls in (ex. American,Indian...). The problem is that I am not sure how to model the database having the fact that every customer may have zero or more registered other
customers as friends. Whilst a customer can have many friend connections, for
each friend connection the date must be recorded.
I assume that I have to create another table called Friends that will contain the cust_id,data as attributes.
My tables are:
Restaurants(rest_id,name,address,date_opened,income_cat_id*)
Category(car_id,title,Description)
Customers(cust_id,name,address,DOB,Mobile_number)
Here is my ER Diagram, but as I said I am not sure if the Recursive relation is right for my Customers table:

Yes, you need another table to model the connections, something like:
Connection(cust_id1, cust_id2, connectdate)

Thank you a very much!
Does that mean that I have to have the following constraints in the Connection table?
CONSTRAINT pk_Connections PRIMARY KEY (cust_id1,cust_id2),
CONSTRAINT fk_Customers_Connections_cust_id1 FOREIGN KEY (cust_id1) REFERENCES Customers(cust_id)
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT fk_Customers_Connections_cust_id2 FOREIGN KEY (cust_id2) REFERENCES Customers(cust_id)
ON DELETE NO ACTION ON UPDATE NO ACTION);

Related

Report Structure in the database

I am building a dynamic structure in a data base so that I can configure reports from backend dynamically. Need your help in designing the backend structure. Here is my idea
Table ReportAccountMap
AccountId
ReportId
IsActive
One account can map to multiple ReportIds, accountid is unique
Table Report_MetaData
StructureId
DataSetName
DataSetSourceId
DataSetSourceServiceAPI
Table Report_Structure
ReportId
StructureId
I am trying to find what constraints to put in the above structure.
Thanks in advance.
Add an id into ReportAccountMap and Report_Structure so your primary key there will be one-dimensional.
ReportAccountMap.AccountId needs to be a foreign key to Account(id)
(ReportAccountMap.AccountId, ReportAccountMap.ReportId) needs to be unique
Report_MetaData.StructureId needs to be a foreign key to Report(StructureId)
Report_MetaData(DataSetSourceId) needs to be a foreign key to DataSetSource(Id)
Report_Structure.ReportId needs to be a foreign key to Report(Id)
Report_Structure.StructureId needs to be a foreign key to (Structure.Id)
At least this is how I understood your intention. It would not hurt to add indexes for the n:m tables taking into account the optimal direction.
Also, ReportAccountMap is needed, since it is different from Account logically and it also has an attribute called IsActive.

SQL Table primary key setting

I'm trying to make a program that has to manage some databases with derby.
In this program, I'm creating two tables, one called "customers" (that has one primary key that is the ID number of the person), and one called "transactions", in which I want one column to reference to the ID of the customer, which I would do through a Foreign key. However, this customer could perform several transactions, so that the actual key would be a combination of the date of the transaction and the id of the customer. Can this be made through the foreign key? Or am I very confused? I would really appreciate any help you guys could give me.
Thanks a lot
It is best to also have a transaction ID. use that id column as the primary key in your transaction table, and have a foreign key user_id to relate to the user.id. Then you can uniquely identify each transaction, all transactions for a user, or query out other things like all transaction within a day for all users, for a set of users and so on.

Last Modified By fields and foreign keys

In SQL Server 2012, I have a User table to store application users. I also have an Organization table which has a LastModifiedBy field in which I would like to store the UserID of the last person to modify the values within the table via an ASPX page. Should I create a foreign key relationship between the LastModifiedBy field and the UserID field within the Users table?
I would also like to add a LastModifiedBy field to the Users table itself. Should/can I create a self referencing foreign key constraint on this table? If this is possible, is it a horrible idea?
Any perspectives on pros and cons of creating these foreign key constraints would be greatly appreciated.
What you are describing is what foreign keys are made for. These foreign keys are at the very core of relational databases. Even if they might give a slight performance impact when inserting new rows, because it has to check if the referenced key exists, it should not be avoided.

Database: One To Many (or One To None) relationship

Im modelling a database in MSSQL 2008.
I have 4 tables.
**User**
userID
userName
**NewsCategory**
newsCategoryID
newsCategoryName
**News**
newsID
newsText
newsCategoryID
**Subscription**
userID
categoryID
I understand that I should have foreign keys between the News and the Category tables. But what should I do with the supscriptions? Should I have a Foreign Key between User and Subscription tables though it's not mandatory to subscribe for something?
Yes you should. Foreign key is used for be sure, that Subscription is created for existing user. Foreign key does not mean, that user should be subscribed on something.
Yes you should have this foreign key because it will prevent a Subscription from existing that does not map to a real user id.
It acts as a constraint on your data.
Subscription is a link (many-many) table and "not mandatory" means there will no row for that user or that user/category.
The foreign key is required to enforce data integrity when you do have subscriptions which will be one or more rows.
Note: In optional parent-child type relationships the FK column(s) will be NULLable to capture "non mandatory". In link tables this is captured by row non-existence
Yes, you should add Foreign keys between User and SubCription tables with Subscription table.
Foreign key contraints are for the validating of adding wrong information to the database. For example, in your Subscription table, there shouldn't be userIDs which are not in the User table and there should be CategoryIDs which are not in the NewsCategory table. These contraints will do the validation for you even if you don't do the validation at the user interface end.
You've gotten some good answers. Let me try to add another.
A SUBSCRIPTION requires both a subscriber and a category. Therefore, each of these columns should not allow nulls. Preventing nulls is not the same thing as a foreign key constraint.
It should also be impossible to insert a row into SUBSCRIPTIONS if the user does not already exist in the USERS table; and it should be impossible to insert a row into SUBSCRIPTIONS if the category does not already exist in the CATEGORIES table. To enforce these rules your SUBSCRIPTIONS table requires two foreign key constraints:
ALTER TABLE SUBSCRIPTIONS ADD CONSTRAINT FK_SUBSCRIPTIONS_USERS FOREIGN KEY(userid) REFERENCES USERS(userid)
ALTER TABLE SUBSCRIPTIONS ADD CONSTRAINT FK_SUBSCRIPTIONS_CATEGORIES FOREIGN KEY(categoryid) REFERENCES CATEGORIES(categoryid)
When you create a foreign key constraint on a table, you are in effect saying to the database engine: make sure that any value that gets inserted into this table already exists in that other table. BTW, a requirement for the constraint to be created is that a unique constraint must be in effect on the column(s) referenced in that table; typically, the referenced column(s) of that table will be the primary key of that table.
By creating a foreign key constraint, you are not saying to the database engine: make sure a row gets inserted into this table. It is quite possible (though it would be unusual) that this table has no rows in it whatsoever. The foreign key constraint simply makes sure that any value that does get inserted into this table has a counterpart in that table.

Error from SQL Server

Hello friends I am getting the following error while making the foreign key
'tbl_course' table saved successfully
'tbl_students' table
- Unable to create relationship 'FK_tbl_students_tbl_course'.
Introducing FOREIGN KEY constraint
'FK_tbl_students_tbl_course' on table
'tbl_students' may cause cycles or
multiple cascade paths. Specify ON
DELETE NO ACTION or ON UPDATE NO
ACTION, or modify other FOREIGN KEY
constraints. Could not create
constraint. See previous errors.
I have the following tables College table, Branch table, Course table and Student table
Course has a foreign key college_id, Branch has a foreign key course_id and I want to make college_id, course_id, branch_id as foreign keys to my Student table but while making course_id and branch_id as foreign key in Student table it generate the error mentioned above...please help me to resolve the above problem.....thanks
According to MS
You receive this error message because in SQL Server, a table cannot appear more than one time in a list of all the cascading referential actions that are started by either a DELETE or an UPDATE statement. For example, the tree of cascading referential actions must only have one path to a particular table on the cascading referential actions tree.
http://support.microsoft.com/kb/321843
Can you live without the cascading deletes? Keep the referential ingegrity but not the referenctial actions (cascades). You could resort to a trigger as a work around if needed.
EDIT:
CREATE TRIGGER [dbo].[tr_College_Delete] ON [dbo].[College]
FOR DELETE
AS
BEGIN
DELETE FROM student
where collegeid in (select collegeid from deleted)
END
not tested.
Why would you add anything but branch_id to the student? From there, you should be able to determine which course the branch belongs to and which college the course belongs to.
If you have
College
College1
College2
College3
Course
Course1, College1
Course2, College1
Course3, College2
Branch
Branch1, Course1
Branch2, Course1
Branch3, Course2
Student
Student1,College3,Course3,Branch1
This is valid from the database standpoint, but makes no sense since the student record should be attached to College1 based on the Branch it's attached to. You know logically that if the student is in a branch with ID Branch1 (or whatever primary key you use, but I use this for illustraion purposes) then they must be in Course1 and College1. By adding the additional information to the Student record, you not only create circular references in the code but put yourself in a position to create a "corrupt" record in the database. Of course you can code around this, but why go to the extra effort when you can simplify the student record to simply (Student1,Branch1) without losing any data?
This is known as database normalization, and it's something that's very important to at least consider when you're building a data model.