I'm writing code in C#.
It has two type of user: distributors and clients.
Clients can see all products of all distributors and can select them with mentioning the number of each product they need.So they make a list of orders.
Distributors can see lists of orders received from all clients to them. The table should contains "distributor id" and "client id" and "list of ordered products" with their cost and numbers which have ordered.
But I have no idea about saving this data to a single table.i want that each row mentions to a single list of orders from a special client to a special distributor.
Can I have a 3D table or an array or there is a better and more efficient way?
Is it possible to do what you want? Yes.
Should you? No.
I mean, let's say you set up your table. A column for the distributor, a column for the client, and a column for your list of orders (let's use XML for the example) :
DistID ClientID Orders
1 1 <item>A</item><item>B</item><item>C</item>
2 1 <item>D</item><item>C</item>
2 2 <item>E</item><item>A</item><item>F</item><item>G</item>
... so what problems will you run into? First, imagine trying to add or remove an order. You'd have to read the full Orders list, change it, and then write it all back to SQL. That's a lot of overhead, especially if your 'list' has a lot of items or if you're doing a lot of order adds/removes.
Worse, what happens when you need to find anyone that's ordered 'B'? You're going to have to do a full text scan on that column - no index seeks, no optimizations, nothing - just to find the matching items.
Here's my suggestion - take a look at "SQL Normalization" - basically, the guidelines on how to organize SQL data efficiently and effectively. Here are some good starter places:
http://www.studytonight.com/dbms/database-normalization.php
https://www.essentialsql.com/get-ready-to-learn-sql-database-normalization-explained-in-simple-english/
https://www.guru99.com/database-normalization.html
Based on the information you give, it seems you want a data model like this:
Distributor
Id
Name
Client
Id
Name
Product
Id
DistributorId (foreign key)
Order
Id
ProductId (foreign key)
ClientId (foreign key)
Number
That way you can store product orders from clients, and make sure distributors see order of their own products by selecting all orders having productId's that are linked to the selected distributor.
Related
At the risk of over-explaining my question, I'm going to err on the side of too much information.
I am creating a bulk upload process that inserts data into two tables. The two tables look roughly as follows. TableA is a self-referencing table that allows N levels of reference.
Parts (self-referencing table)
--------
PartId (PK Int Non-Auto-Incrementing)
DescriptionId (Fk)
ParentPartId
HierarchyNode (HierarchyId)
SourcePartId (VARCHAR(500) a unique Part Id from the source)
(other columns)
Description
--------
DescriptionId (PK Int Non-Auto-Incrementing)
Language (PK either 'EN' or 'JA')
DescriptionText (varchar(max))
(I should note too that there are other tables that will reference our PartID that I'm leaving out of this for now.)
In Description, the combo of Description and Language will be unique, but the actual `DescriptionID will always have at least two instances.
Now, for the bulk upload process, I created two staging tables that look a lot like Parts and Description but don't have any PK's, Indexes, etc. They are Parts_Staging and Description_Staging.
In Parts_Staging there is an extra column that contains a Hierarchy Node String, which is the HierarchyNode in this kind of format: /1/2/3/ etc. Then when data is copied from the _Staging table to the actual table, I use a CAST(Source.Column AS hierarchyid).
Because of the complexity of the ID's shared across the two tables, the self-referencing id's and the hierarchyid in Parts, and the number of rows to be inserted (possible in the 100,000's) I decided to 100% compile ALL of the data in a C# model first, including the PK ID's. So the process looks like this in C#:
Query the two tables for MAX ID
Using those Max ID's, compile a complete model of all the data for both tables (inlcuding the hierarchyid /1/2/3/)
Do a bulk insert into both _Staging Tables
Trigger a SP that copies non-duplicate data from the two _Staging tables into the actual tables. (This is where the CAST(Source.Column AS hierarchyid) happens).
We are importing lots of parts books, and a single part may be replicated across multiple books. We need to remove the duplicates. In step 4, duplicates are weeded out by checking the SourcePartId in the Parts table and the Description in the DescriptionText in the Description table.
That entire process works beautifully! And best of all, it's really fast. But, if you are reading this carefully (and I thank if you are) then you have already noticed one glaring, obvious problem.
If multiple processes are happening at the same time (and that absolutely WILL happen!) then there is a very real risk of getting the ID's mixed up and the data becoming really corrupted. Process1 could do the GET MAX ID query and before it manages to finish, Process2 could also do a GET MAX ID query, and because Process1 hasn't actually written to the tables yet, it would get the same ID's.
My original thought was to use a SEQUENCE object. And at first, that plan seemed to be brilliant. But it fell apart in testing because it's entirely possible that the same data will be processed more than once and eventually ignored when the copy happens from the _Staging tables to the final tables. And in that case, the SEQUENCE numbers will already be claimed and used, resulting in giant gaps in the ID's. Not that this is a fatal flaw, but it's an issue we would rather avoid.
So... that was a LOT of background info to ask this actual question. What I'm thinking of doing is this:
Lock both of the tables in question
Steps 1-4 as outlined above
Unlock both of the tables.
The lock would need to be a READ lock (which I think is an Exclusive lock?) so that if another process attempts to do the GET MAX ID query, it will have to wait.
My question is: 1) Is this the best approach? And 2) How does one place an Exclusive lock on a table?
Thanks!
I'm not sure in regards to what's the best approach but in terms of placing an 'exclusive' lock on a table, simply using with (TABLOCKX) in your query will put one on the table.
If you wish to learn about it;
https://msdn.microsoft.com/en-GB/library/ms187373.aspx
in my DB I have 3 tables like below :
I also have an Autocomplete field in my page in which visitors can search by Country, Province or City and as you know after inserting 3 letter, the search should be conducted by each letter that is inserted. now it seems so costly searching through each table in turn and successively. I also know that City is the most searched field. so what should be the best approach for searching in my case? I should mention that I didn't deploy my web app yet and I can change tables and it's relations.
a code sample would be great.
thanks in advance
MA
Here you can do two things
Create a flat(denormalized data) table combining all the three tables and do the searching in that. Also, you may have to create some triggers on this table to sync the flat table data with data of the actual table.
In a second way, you have to search each table conditionally. Like in your case city is most likely to search then,
a. Search each table
b. Transform the results into a common type
c. Merge the results
d. Sort/select from this merged list
I'm a personal trainer and I have some programming background but I don't know much about database.. I'm trying to create a program where I can store my clients personal information and especially if they have any health problems and medicines they use so that in case something happens I can quickly find the information needed so what I'm using
Xampp, and C# ( open to suggestions if I will be more successful with a different language program)
what I want is to create three tables;
1-personal_information (id(primary key) ,first_name,second_name,date of birth, 'and some other information)
2-health_information ( disease, medicines)
3-size ( kg, and sizes of the body parts like chest, biceps, triceps etc.. and date )
but one client may have more than one disease and may use more than one medicine per a disease) and
also I want to measure my clients once in 2 months and add the new sizes without losing the previous values
so I need an array of health_information and size per id but how do I do that in mysql? I'm sure that it's something very easy but just can't figure it out
thanks in advance :)
In your second table you'll want a column called personal_information_id which will correspond to a row in the personal_information table. When you want to retrieve data for specific person execute a query similar to Select * from health_information where personal_information_id = 12345. This will return all the rows in the second table that are related to patient 12345.
Obviously you'll want to do something similar for your size table.
It's been a long time since I've done any serious work with relational database, and despite spending the last two hours searching the Internet and taking my best guesses, I just can't work out the necessary SQL Query expression.
I have three related tables:
Players - Contains a list of players
Coaches - Contains a list of coaches
Evaluations - Stores each coach's evaluation of each player as a number.
Each record in the third table therefore includes a field with the PlayerID, CoachID and the rating.
If I have 10 players and 3 coaches, then table 3 should have 30 records in it.
In order to populate these tables, I want to show the coaches names (pulled from the Coaches table) and display them as Columns in a DataGridView that has a Row for each player so that when you enter a value in a player's row under the coach's column, the value get's stored in Table 3 with the appropriate Player and Coach IDs.
I know I've done something like this year's ago in Microsoft Access, but I can't figure out how to build the Query in my Dataset so that I can bind it to the DataGridView.
I tried using the following SQL Query, but it doesn't let me edit the values in the Coach1 and Coach2 columns. I suspect that's because I have a one-many relationship between PlayerList and Evaluations and a one-many relationship between Coaches and Evaluations:
SELECT PlayerList.Number, PlayerList.Name, PlayerList.Year, PlayerList.Height, PlayerList.Notes, PlayerList.AverageSkill, AVG(Evaluations.Skill) AS CoachSkill,
'SELECT Skill FROM Evaluations
WHERE (PlayerID = PlayerList.Number) AND (CoachID = 1)' AS Coach1,
'SELECT Skill FROM Evaluations
WHERE (PlayerID = PlayerList.Number) AND (CoachID = 2)' AS Coach2
FROM Evaluations RIGHT OUTER JOIN
PlayerList ON Evaluations.PlayerID = PlayerList.Number
GROUP BY PlayerList.Number, PlayerList.Name, PlayerList.Year, PlayerList.Height, PlayerList.Notes, PlayerList.AverageSkill
Any help would be appreciated.
Application details: I'm working with C# in Visual Studio Express with a SQL-Server-CE database.
A little more reading leads me to believe that what I want is a PIVOT function which SQL-Server-CE doesn't support.
Thank you.
You could create new DataRows and add columns dynamically. Then add all your created rows to a DataGridView.
This something related to nested Grid, as hierarchical data
go through this link which in detailed explain how to use gridview/datgrids in scenarios like yours.
http://msdn.microsoft.com/en-us/magazine/cc164077.aspx
hope this will resolve your issue.
I have an application that I need to query lifetables (for insurance calculation).
I was thinking about using XML to store the data, but thought it was a little big, but maybe a little small for using a full-fledged database. So I chose to use SQLite.
In my application, I have enums defining a few different things. For example, GENDER.Male, GENDER.Female. and JOBTYPE.BlueCollar, JOBTYPE.WhiteCollar. etc etc.
I have some methods that look like this: (example)
FindLifeExpectancy(int age, GENDER gender);
FindDeathRate(int age, JOBTYPE jobType);
So my question is: How do you model enums in a database? I don't think it is best practice to use 0 or 1 in the database to store JOBTYPE because that would be meaningless to anyone looking at it. But if you used nvarchar, to store "BlueCollar", there would be a lot of duplicate data.
I don't think GENDER or JOBTYPE should have an entire class, or be apart of the entity model because of the little information they provide.
How is this normally done?
Thanks.
I prefer to statically map my enums in my program to a lookup table in my database. I rarely actually use the lookup table to do a join. As an example I might have the following tables:
Gender
GenderID Name
1 Male
2 Female
Accounts
AccountID GenderID FirstName LastName
1 1 Andrew Siemer
2 2 Jessica Siemer
And in code I would then have my enum defined with the appropriate mapping
public enum Gender
{
Male = 1,
Female = 2
}
Then I can use my enum in code and when I need to use the enum in a LINQ to SQL query I just get its physical value like this
int genderValue = (int)Enum.Parse(typeof(Gender), Gender.Male));
This method may make some folks out there a bit queezy though given that you have just coupled your code to values in your database! But this method makes working with your code and the data that backs that code much easier. Generally, if someone swaps out the ID of a lookup table, you are gonna be hosed in some way or another given that it is mapped across your database any how! I prefer the readability and ubiquitous nature of this design though.
While it's unlikely that you will be adding a new gender, I wouldn't be so sure about the jobtype enum. I'd have used a separate table for both, and have foreign keys to this table every where I need to reference them. The schema will be extensible, the database will automatically check that only possible values are saved in the referencing tables.
The SQL equivalent of 'enums' are lookup tables. These are tables with two (sometimes more) columns:
a code, typically short, numeric or character (ex: 'R', 'S', 'M'...)
a text definition (ex: 'Retired', 'Student', 'Military'...)
extra columns can be used to store definitions, or alternate versions of the text for example a short abbreviation for columnar reports)
The short code is the type of value stored in the database, avoiding the replication you mentioned. For relatively established categories (say Male/Female), you may just use a code, without 'documenting' it in a lookup table.
If you have very many different codes, it may be preferable to keep their lookup in a single SQL table, rather than having a proliferation of dozen of tables. You can simply add a column that is the "category", which itself is a code, designating the nature of the group of codes defined in this category ("marital status", "employment", "education"...)
The info from the lookup tables can be used to populate drop downs and such, in the UI, wherey the end-user sees the clear text but the application can use the code to query the database. It is also used in the reverse direction, to produce the clear text for codes found in the database, for displaying results list and such.
A JOIN construct at the level of SQL is a convenient way to relate the lookup table and the main table. For example:
SELECT Name, Dob, M.MaritalStatus
FROM tblCustomers C
LEFT OUTER JOIN tblMaritalLkup M ON C.MStatus = M.Code
WHERE ...