Selecting data from multiple tables based on PK - ASP.NET - c#

I am looking to select data from multiple tables and insert into respective text boxes. I can have one table that hold all the data, but as I want to apply normalization to the data sets, I will have to split the data.
I already know that I can use :
SELECT *
FROM users
WHERE Username = UserNametxt.Text.Trim()
and then addWithValue etc.
How would I do this using a PK from one table linked to other tables as a FK?
Table users:
id (pk)
email
password
last_login
Table address:
id (fk to users.id)
houseNumber
StreetName
City
Table postcode:
id (fk to users.id)
PostCode
The above is a rough sample of what the data tables will be.

First of all, you should change the structure of your tables. In order to properly normalize DB, tables address and postcode should have their own id (PK), which does not depend on data from other tables.
If you leave it that way, you won't get rid of data duplication (which is one of the main reasons to normalize DB)
So it would look like that:
Table addresses:
id (PK)
userId (FK)
houseNumber
streetName
city
Table postcodes:
id (PK)
userId (FK)
postCode
And then you need to get information. You need to use JOIN to somehow connect tables and get information you need
SELECT * FROM users
LEFT JOIN addresses ON adresses.UserId=users.Id
LEFT JOIN postcodes ON postcodes.UserId=users.Id
WHERE ...

Related

Insert to a table all records from a column from another table with a standard value

I have two tables, shops and products. Table shop with columns shopId (PK) and shopName. Another table Products has columns productId (PK) and productName. Because I have a relationship many-many between two tables I create another table shopProduct with two columns shopId and productId.
For example I have shop1 with id=1 and I have shop2 with id=2, product1 with id=1 and product2 with id=2. and the records of the table shopProduct is 1-1 ,2-2.
But now I want to have a product3 with id=3 that apply to all shops.
I consider in the real problem that i have about 250 shops.
How can implement this without a stored procedure?
I don't want to do of course 250
insert into shopProduct (shopId, productId)
values (#shopId,#productId).
Can I do for loop for example to feed the the shopId value every time?The other value for product id is the same every time.
From my understanding of this question, try this... Seems too simple, but...
Insert into ShipProduct (ProductID, ShopID)
Select 3, ShopID
From Shops

Multiple database records

I want to store emergency help line contacts in database from ASP.NET web site . . .this contacts will be assign to particular locations of different cities. . .
For eg: City=Mumbai and then for Mumbai City there will be various locations like Dadar, Andheri, Borivali , etc .
I have designed a form
now, the problem is that , there can be one airport for multiple locations of a particular city then also i have to enter the entire information for each and every location . . . So is there any way to avoid multiple entries ?
You can use following table schema, and design you form accordingly
Location Table
LocationID (Primary Key)
CountryID (Foreign Key)
CityID (Foreign Key)
ContactID (Foreign Key)
Location
City Table
CityID(Primary Key)
City
Country Table
CountryID(Primary Key)
Country
Service Table
ServiceID(Primary Key)
Service --Airport/Ambulance/fire...
Contact Table
ContactID (Primary Key)
ServiceID (Foreign Key)
Description --AirportName/HospitalName
Contact --Contact Number
UPDATE (Form Design Tips)
Form to add records to City/Country/Service Tables (They are quite simple you just need to check duplicate entry/ Required fields.
For Contact Table use Drop Down for Service that is populated from Service Table
For Location use Drop Downs for Country,City and Contact that are populated from respective tables.
Use INNER JOINS to join the tables and display the desired Results

SQL Structure Stores, Countries, Districts and Other Important Criteria

I am sorry if this is a bit broad but I've been working on a structure for a couple of days and I can't seem to figure this out the cleanest and most efficient way to do this. I could share the tables that I've created for now but I really think it's not close to how a proper diagram should be.
Let me describe my problem a bit:
I have Stores, Countries, Districts, Categories.
Each store could belong to different Countries/Districts enabling Store Branch manipulation.
Of course a store could belong to multiple Categories too, for example Store X could be under both Food and Beverages and Night Clubs.
A Country will have multiple Districts and Stores, and a Store could have many Countries and Districts.
I am writing my application using C# and I don't have problems creating data-layer objects and classes. But I need the proper MSSQL structure to manipulate and filter down data based on given criteria.
The most important criteria would be: Going through Countries as a first step, then locating Stores within that Country as a global view, then it's important to sort Stores based on Districts and/or Categories within that Country.
Please let me know if you need me to share what I have for now, but since I'm on Stack Overflow asking this question you can guess that I'm doing this the wrong way.
Anyway, if you could shed some light on this issue and explain how things should be done properly I would highly appreciate it.
Thanks in advance.
Whenever you have many-to-many relationships (e.g. one district may contain many stores; one store may be contained by many districts), you are going to need to use cross-reference tables between those entities.
I'm assuming that a particular district may only be contained by one single country. Here is how I would model out your schenario:
countries(country_id [PK], name, ...)
districts(district_id [PK], country_id [FK], name, ...)
districts_has_stores(district_id [PK], store_id [PK])
stores(store_id [PK], name, ...)
categories_has_stores(category_id [PK], store_id [PK])
categories(category_id [PK], name, ...)
In ER:
districts_has_stores and categories_has_stores are the cross-reference tables representing the many-to-many relationships between your entities.
Based off of this model, you can retrieve all stores within a particular country, and order the stores by district name using the following SQL:
SELECT
c.*
FROM
districts a
INNER JOIN
districts_has_stores b ON a.district_id = b.district_id
INNER JOIN
stores c ON b.store_id = c.store_id
WHERE
a.country_id = <country_id here>
ORDER BY
a.name
Retrieving the count of stores in each country:
SELECT
a.country_id,
COUNT(*) AS store_count
FROM
districts a
INNER JOIN
districts_has_stores b ON a.district_id = b.district_id
GROUP BY
a.country_id
Edit: As per your comment to this answer, here's an example of how you can retrieve all stores that have a category_id of 1:
SELECT
b.*
FROM
categories_has_stores a
INNER JOIN
stores b ON a.store_id = b.store_id
WHERE
a.category_id = 1
Retrieving all stores in a particular category_id (1) and filtering the result to only include those stores within either districts 4 or 5.
SELECT DISTINCT
b.*
FROM
categories_has_stores a
INNER JOIN
stores b ON a.store_id = b.store_id
INNER JOIN
districts_has_stores c ON b.store_id = c.store_id
WHERE
a.store_id = 1 AND
c.district_id IN (4,5)
It's very easy, you have StoryCategory to solve the "many stores can have many categories" problem. The District and Country tables allow you to store the location of your store.
I advise you to look at the following documentation to expand your database design knowledge:
Many To Many
10 useful articles
I think below should work for you.
Countries
=========
CountryId, CountryName
Districts
=========
DistrictId, CountryId, DistrictName
Stores
=========
StoreId, DistrictId, Storename
Categories
=========
CategoryId, Categoryname
StoreCategories
=========
Storecategoryid, StoreId, CategoryId
You would have a country table with an identity column. Each store can "be-a" Category, you'd have to have an association table which is a child table of the store table which would have a store ID and the ID from the Category table. Each store would belong to a country so your store table would store the ID of the country from the Country table. Similar to the Category, your District table would have a child table which stores the ID of the District and of the Country (since each district can have multiple countries)
Store Table
ID INT IDENTITY PK
Category FK
Country FK (where it actually lives, a 1 to 1)
District FK
Category Table
ID INT IDENTITY PK
StoreCategory Table
StoreID FK
CategoryID FK
Country Table
ID INT IDENTITY PK
District Table
ID INT IDENTITY PK
DistrictCountry Table
DistrictID FK
CountryID FK

Self Referential Entity - MANY TO MANY

Just after some advice regarding this database design situation.
So I have two tables in the database.
Table 1: Patients
Table 2: Claimants
Patients holds attributes data on a private patient, so details about the person, his/her birthday, names, medical conditions, etc etc..
Claimants is the entity who pays on behalf of the patient, so Claimant can be a patient himself, another person, a business (who pays for work injury), private healthcare provider, government bodies etc etc..
Patients and claimants have IDs who are foreign keys in other tables such as invoices, receipts etc...
One Patient can have multiple Claimants (More than one entity can pay on his behalf), each Claimant can have multiple patients.
On further investigation, I've identified that many of the attributes of Patients and Claimants overlap as a Patient can pay for himself thus is a private Claimant.
My thinking is to merge the two tables into one and simply call it accounts and have a claimantType field to identify the type of the account, be it private, healthcare, business or government.
What potential practical drawbacks do I need to keep in mind with this change? Apart from the changing the other linked tables in database?
EDIT: Just to make it clear, There's already a junctional table PatientClaimants which basically just map the patients to the claimants. Thanks!
Merging these two tables I believe is wrong.
A patient is always a human. So it cannot be a business or an organisation.
I believe here you have:
Address
=======
......
Person
=======
AddressId (FK)
BusinessEntity
==============
AddressId (FK)
Patient
=======
PersonId (FK)
Claimant
========
PersonId (FK)
BusinessEntityId (FK)
Here PersonId or BusinessId one of them can be null.
You could either (a) put in an intersection table that relates patient IDs to claimant IDs, or (b) as you discussed, merge them together - but if you already have data out there that could be problematic.
You could also set up a demographics table that shows common data between patients and claimants and references an abbreviated patient/claimant table - this way you do not break your existing structure.

ASP.NET C# problem with Table and SQL logic

Hey I have 3 tables called STUDENT, COURSE and ENROLLMENT. STUDENT has a PK of S_ID(student ID) and COURSE has PK of C_ID(course ID). In enrollment it only has S_ID and C_ID. I have an object data source to show all the students name (in text, and S_ID as the value) in a drop down menu and it will show which courses he is registered in when clicked, using a datagrid and another object data source. I wont to have the student to have multiple courses to be registered too, but I cant do that because you cannot have the same ID in the COURSE table, so every student is only registered to one course.
Is there some sort of option to have same ID's in a table?
If not, then I must some how manipulate the string in C_ID in the COURSE table because all the courses start with ISDVXXX or ITSXXXX or HGFXXXX. This may be hard to understand but hopefully someone will help.
An example may help
So if a student named Joe with a S_ID of 123 is registered to ISDV, he will be registered to all the courses that start with ISDV. But my problem is that my COURSE table has to have unique ID for each course such as ISDV123, ISDV346, ISDV395 etc... so this also ruins my enrollment table because I cannot simply have ISDV in there, it needs a specific course but he is registered to all of them. Any more clarification will be given :P Thanks...
What you're trying to solve is a multi-valued attribute problem. Basically, you have two tables where one (students) has a primary key which is a foreign key in another table (classes). You don't want to have multiples of the same class in the classes table, but you do want a student to be able to have multiple classes.
So, there is a very simple fix, you create another table which contains at least these two columns: student_id and class_id. This way, you could have a single class that multiple students are linked to, and also multiple classes to which a student can be linked to.
What you are looking for is a many to many relationship - i.e. a single student can have multiple courses, and a single course can have multiple students. So your link table (is this what you intended enrollment for?) should have two columns, one for the course ID and one for the student ID.
So if you had student 123 and student 234, and courses ABC and XYZ, your table would look something like:
S_ID C_ID
123 ABC
123 XYZ
234 ABC
Now, for your PK on enrollments you could either use a composite key, or add a unique integer RowId (Identity or HiLo algorithm).
In that case, your enrollment table would look something like this:
S_ID C_ID RowID
123 ABC 1
123 XYZ 2
234 ABC 3
Then, to see what classes a student was in, you could do something like
Select * from courses c
inner join enrollments e
on c.C_ID = e.C_ID
AND e.S_ID = #StudentId
Your Enrollment table stands for the m:n relationship between the Studend and Course tables.
For instance your student with S_ID = 69 is Enrolled to the Courses with C_ID = ISDVXXX , C_ID = ITSXXXX, C_ID = HGFXXXX
A Student can be Enrolled to more Courses and more Students can be Enrolled to the same Course, that's why you have your Enrollment table. In our example, the Enrollment will have the following rows:
(69, ISDVXXX), (69, ITSXXXX), (69, HGFXXXX).
If later a student with the S_ID = 96 joins to the Course with C_ID = ISDVXXX, the following will be the new rows of the Enrollment table:
(69, ISDVXXX), (69, ITSXXXX), (69, HGFXXXX), (96, ISDVXXX).
The important thing to understand here is that each row in the Enrollment table stands for a Student Enrolled to a Course and there is no need to other fields than the ID of the Student and the ID of the Course, for these two fields together identify an Enrollment.

Categories