Tables not showing anything when creating new one - sql

I have problem with SQL .
I am trying to create tables from other tables with foreign keys. The table is created normally without problem but when I'm trying to see the data inside the table there is none of the data inside! Anyone who knows?
-- Here is my table with the foreign keys
CREATE TABLE StaffXCustomersXMeals(
--MealID int FOREIGN KEY REFERENCES Meals(MealID),
--CustomersID int FOREIGN KEY REFERENCES Customers(CustomersID),
--StaffID int FOREIGN KEY REFERENCES Staff(StaffID)
)

You might want to consider reading up on the concept of a SQL View - think of it as a "virtual table based on the result-set of an SQL statement." When you create a view based on the JOIN between multiple tables, it saves your query and you can then select from it like you would a table.
For example, you might have the following:
CREATE VIEW StaffCustomerMeals
AS
SELECT
m.MealID,
c.CustomersID,
s.StaffID
FROM
Meals m
LEFT JOIN
Customers c ON
m.SomeIDThatMeansThisCustomer = c.CustomersID
LEFT JOIN
Staff s ON
m.SomeIDThatMeansAStaffMember = s.StaffID
You need to define these relationships in accordance with your own schema - it's your homework assignment, so do your best to figure it out. A couple more questions to consider:
Does a meal always have both a customer and a staff member, or are they customers who might happen to be staff members?
Should you include other information besides the IDs (e.g., CustomerName, StaffMemberDepartment, MealPrice, PurchaseDate)

You didn't enter any data. You only said that whatever data entered must reference the other tables. So you cannot enter invalid meals for instance.
You need INSERT statments to fill the table with whatever data you need.

Related

Extending table with another table ... sort of

I have a DB about renting cars.
I created a CarModels table (ModelID as PK).
I want to create a second table with the same primary key as CarModels have.
This table only contains the number of times this Model was searched on my website.
So lets say you visit my website, you can check a list that contains common cars rented.
"Most popular Cars" table.
It's not about One-to-One relationship, that's for sure.
Is there any SQL code to connect two Primary keys together ?
select m.ModelID, m.Field1, m.Field2,
t.TimesSearched
from CarModels m
left outer join Table2 t on m.ModelID = t.ModelID
but why not simply add the field TimesSearched to table CarModels ?
Then you dont need another table
Easiest is to just use a new primary key on the new table with a foreign key to the CarModels table, like [CarModelID] INT NOT NULL. You can put an index and a unique constraint on the FK.
If you reeeealy want them to be the same, you can jump through a bunch of hoops that will make your life Hell, like creating the table from the CarModels table, then setting that field as the primary key, then whenever you add a new CarModel you'll have to create a trigger that will SET IDENTITY_INSERT ON so you can add the new one, and remember to SET IDENTITY_INSERT OFF when you're done.
Personally, I'd create a CarsSearched table that holds ThisUser selected ThisCarModel on ThisDate: then you can start doing some fun data analysis like [are some cars more popular in certain zip codes or certain times of year?], or [this company rents three cars every year in March, so I'll send them a coupon in January].
You are not extending anything (modifying the actual model of the table). You simply need to make INNER JOIN of the table linking with the primary keys being equal.
It could be outer join as it has been suggested but if it's 1:1 like you said ( the second table with have exact same keys - I assume all of them), inner will be enough as both tables would have the same set of same prim keys.
As a bonus, it will also produce fewer rows if you didn't match all keys as a nice reminder if you fail to match all PKs.
That being said, do you have a strong reason why not to keep the said number in the same table? You are basically modeling 1:1 relationship for 1 extra column (and small one too, by data type)
You could extend (now this is extending tables model) with the additional attribute of integer that keeps that number for you.
Later is preferred for simplicity and lower query times.

Assign unique ID to duplicates in Access

I had a very big excel spreadsheet that I moved into Access to try to deal with it easier. I'm very much a novice. I'm trying to use SQL via Access.
I need to assign a unique identifier to duplicates. I've seen people use DENSE_RANK in SQL but I can't get it to work in Access.
Here's what I'm trying to do: I have a large amount of patient and sample data (20k rows). My columns are called FULL_NAME, SAMPLE_NUM, and DATE_REC. Some patients have come in more than once and have multiple samples. I want to give each patient a unique ID that I want to call PATIENT_ID.
I can't figure out how to do this, aside from typing it out on each row. I would greatly appreciate help as I really don't know what I'm doing and there is no one at my work who can help.
To illustrate the previous answers' textual explanation, consider the following SQL action queries which can be run in an Access query window one by one or as VBA string queries with DAO's CurrentDb.Execute or DoCmd.RunSQL. The ALTER statements can be done in MSAcecss.exe.
Create a Patients table (make-table query)
SELECT DISTINCT s.FULL_NAME INTO myPatientsTable
FROM mySamplesTable s
WHERE s.FULL_NAME IS NOT NULL;
Add an autonumber field to new Patients table as a Primary Key
ALTER TABLE myPatientsTable ADD COLUMN PATIENT_ID AUTOINCREMENT NOT NULL PRIMARY KEY;
Add a blank Patient_ID column to Samples table
ALTER TABLE mySamplesTable ADD COLUMN PATIENT_ID INTEGER;
Update Patient_ID Column in Samples table using FULL_NAME field
UPDATE mySamplesTable s
INNER JOIN myPatientsTable p
ON s.[FULL_NAME] = p.[FULL_NAME]
SET s.PATIENT_ID = p.PATIENT_ID;
Maintain third-norm principles of relational databases and remove FULL_NAME field from Samples table
ALTER TABLE mySamplesTable DROP COLUMN FULL_NAME;
Then in a separate query, add a foreign key constraint on PATIENT_ID
ALTER TABLE mySamplesTable
ADD CONSTRAINT PatientRelationship
FOREIGN KEY (PATIENT_ID)
REFERENCES myPatientsTable (PATIENT_ID);
Sounds like FULL_NAME is currently the unique identifier. However, names make very poor unique identifiers and name parts should be in separate fields. Are you sure you don't have multiple patients with same name, e.g. John Smith?
You need a PatientInfo table and then the SampleData table. Do a query that pulls DISTINCT patient info (apparently this is only one field - FULL_NAME) and create a table that generates unique ID with autonumber field. Then build a query that joins tables on the two FULL_Name fields and updates a new field in SampleData called PatientID. Delete the FULL_Name field from SampleData.
The command to number rows in your table is [1]
ALTER TABLE MyTable ADD COLUMN ID AUTOINCREMENT;
Anyway as June7 pointed out it might not be a good idea to combine records just based on patient name as there might be duplicates. Better way will be treat each record as unique patient for now and have a way to fix patient ID when patient comes back. I would suggest to go this way:
create two new columns in your samples table
ID with autoincrement as per query above
patientID where you will copy values from ID column - for now they will be same. But in future they will diverge
copy columns patientID and patientName into separate table patients
now you can delete patientName column from samples table
add column imported to patients table to indicate, that there might be some other records that belong to this patient.
when patients come back you open his record, update all other info like address, phone, ... and look for all possible samples record that belong to him. If so, then fix patient id in those records.
Now you can switch imported indicator because this patient data are up to date.
After fixing patientID for samples records. You will end up with patients with no record in samples table. So you can go and delete them.
Unless you already have a natural key you will be corrupting this data when you run the distinct query and build a key from it. From your posting I would guess a natural key would be SAMPLE_NUM. Another problem is that if you roll up by last name you will almost certainly be combining different patients into one.

SQL Server foreign key to multiple tables

I have the following database schema:
members_company1(id, name, ...);
members_company2(id, name, ...);
profiles(memberid, membertypeid, ...);
membertypes(id, name, ...)
[
{ id : 1, name : 'company1', ... },
{ id : 2, name : 'company2', ... }
];
So each profile belongs to a certain member either from company1 or company2 depending on membertypeid value
members_company1 ————————— members_company2
———————————————— ————————————————
id ——————————> memberid <——————————— id
name membertypeid name
/|\
|
|
profiles |
—————————— |
memberid ————————+
membertypeid
I am wondering if it's possible to create a foreign key in profiles table for referential integrity based on memberid and membertypeid pair to reference either members_company1 or members_company2 table records?
A foreign key can only reference one table, as stated in the documentation (emphasis mine):
A foreign key (FK) is a column or combination of columns that is used
to establish and enforce a link between the data in two tables.
But if you want to start cleaning things up you could create a members table as #KevinCrowell suggested, populate it from the two members_company tables and replace them with views. You can use INSTEAD OF triggers on the views to 'redirect' updates to the new table. This is still some work, but it would be one way to fix your data model without breaking existing applications (if it's feasible in your situation, of course)
Operating under the fact that you can't change the table structure:
Option 1
How important is referential integrity to you? Are you only doing inner joins between these tables? If you don't have to worry too much about it, then don't worry about it.
Option 2
Ok, you probably have to do something about this. Maybe you do have inner joins only, but you have to deal with data in profiles that doesn't relate to anything in the members tables. Could you create a job that runs once per day or week to clean it out?
Option 3
Yeah, that one may not work either. You could create a trigger on the profiles table that checks the reference to the members tables. This is far from ideal, but it does guarantee instantaneous checks.
My Opinion
I would go with option 2. You're obviously dealing with a less-than-ideal schema. Why make this worse than it has to be. Let the bad data sit for a week; clean the table every weekend.
No. A foreign key can reference one and only one primary key and there is no way to spread primary keys across tables. The kind of logic you hope to achieve will require use of a trigger or restructuring your database so that all members are based off a core record in a single table.
Come on you can create a table but you cannot modify members_company1 nor members_company2?
Your idea of a create a members table will require more actions when new records are inserted into members_company tables.
So you can create triggers on members_company1 and members_company2 - that is not modify?
What are the constraints to what you can do?
If you just need compatibility on selects to members_company1 and members_company2 then create a real members table and create views for members_company1 and members_company2.
A basic select does not know it is a view or a table on the other end.
CREATE VIEW dbo.members_company1
AS
SELECT id, name
FROM members
where companyID = 1
You could possible even handle insert, updates, and deletes with instead-of
INSTEAD OF INSERT Triggers
A foreign key cannot reference two tables. Assuming you don't want to correct your design by merging members_company1 and members_company2 tables, the best approach would be to:
Add two columns called member_company1_id and member_company2_id to your profiles table and create two foreign keys to the two tables and allow nulls. Then you could add a constraint to ensure 1 of the columns is null and the other is not, at all times.

Unable to join 6 tables with out any primary or foreign keys - Out of memory

I have six tables, which unfortunately does not have any primary/foreign key-relations encoded. I've tried to create a view, however I am more than happy with just a table.
I've managed to join the six tables, but after returning 33.5 million rows (cleanInventtrans has 1.7 million rows and every time more tables are added, I am assuming the tables are multiplied by the combination of the previous table) I run out of memory. Now, I realize this is not the correct way of doing this, if it was I'd get a result I am assuming.
I've looked at a couple of questions online
http://www.daniweb.com/web-development/databases/ms-sql/threads/123446/problem-using-join-with-six-tables
SQL joining 6 tables
Unable to relate two MySQL tables (foreign keys)
And I've looked at
http://www.techonthenet.com/sql/joins.php
However, they assume there is a primary-foreign key relationship, my tables do not have this but there are fields which correspond, between the various tables, as seen in the SQL code below. I use these to match up the tables, but somewhere along the line, I am clearly doing it wrong.
I understand that by doing it like this I am essentially multiplying results with each table I join with. I was hoping there was a more clever/correct way of doing it which reduces the amount of results to a management size.
I am unfortunately unable to provide a create statement.
The code I am using:
SELECT dbo.AX_SALESLINE.SALESID, dbo.AX_SALESLINE.ITEMID, dbo.AX_SALESLINE.QTYORDERED, dbo.AX_SALESLINE.SALESPRICE, dbo.AX_SALESLINE.LINEPERCENT,
dbo.AX_SALESLINE.LINEAMOUNT, dbo.AX_SALESLINE.SALESQTY, dbo.AX_SALESLINE.CONFIRMEDDLV, dbo.CleanInventTrans.COSTAMOUNTPOSTED,
dbo.CleanInventTrans.DATEPHYSICAL, dbo.AX_CUSTPACKINGSLIPJOUR.DELIVERYDATE, dbo.AX_SALESTABLE.CUSTACCOUNT, dbo.AX_SALESTABLE.SALESTYPE,
dbo.AX_SALESTABLE.SALESSTATUS, dbo.AX_CUSTPACKINGSLIPJOUR.QTY, dbo.AX_PRODTABLE.PRODID
FROM dbo.AX_CUSTPACKINGSLIPJOUR INNER JOIN
dbo.AX_SALESTABLE INNER JOIN
dbo.CleanInventTrans INNER JOIN
dbo.AX_INVENTTABLE ON dbo.CleanInventTrans.ITEMID = dbo.AX_INVENTTABLE.ITEMID INNER JOIN
dbo.AX_PRODTABLE ON dbo.AX_INVENTTABLE.ITEMID = dbo.AX_PRODTABLE.ITEMID INNER JOIN
dbo.AX_SALESLINE ON dbo.AX_INVENTTABLE.ITEMID = dbo.AX_SALESLINE.ITEMID ON dbo.AX_SALESTABLE.SALESID = dbo.AX_SALESLINE.SALESID ON
dbo.AX_CUSTPACKINGSLIPJOUR.SALESID = dbo.AX_SALESLINE.SALESID
Edit:
Salesline and salestable can be related via P/F-keys, however inventtable and salesline does not have a relationship beyond having a column named itemid, which is the same in both. But these have duplicates and can not function as keys.
Edit2:
Salesline and inventtable cannot be related for some reason:
'AX_INVENTTABLE' table saved successfully
'AX_SALESLINE' table
- Unable to create relationship 'FK_AX_SALESLINE_AX_INVENTTABLE'.
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_AX_SALESLINE_AX_INVENTTABLE". The conflict occurred in database "VS1", table "dbo.AX_INVENTTABLE", column 'ITEMID'.
I've checked the itemid in inventtable, it is unique, and there are multiple of the itemid in the salesline - however not all ID's are numerical in nature, some contain letters. I am not sure if this is what is causing the problem yet.
Edit3:
Foreign-primary relation fails because there are IDs in salines which are not present in the inventtable. Very odd.
Don't bring back all of the rows from these 6 tables. If there are 1million plus rows in some of the tables at least filter on one of these tables, i.e.the CleanIventTrans table using a WHERE clause. If you're not going to add primary and foreign keys, at least add indexes to help improve performance.

Create foreign key with non unique column in SQL Server

I am dealing with a table that contains both cars and owners (table CO). I am creating another table to contain attributes for an owner (table OwnerAttributes), that a user can assign to through a GUI. My problem lies in the fact that owners are not unique and since I am using SQL Server I cannot create a foreign key on them. There is an id in the table, but it identifies the car and owner as a whole.
The idea I had to get around this problem is to create a new table (table Owners) that contains distinct owners, and then adding a trigger to table CO that would update the Owners with any changes. I can then use table Owners for my OwnerAttributes table and solve my problem.
The question I want answered is if there is a better way to do this?
I am using a preexisting database, that is heavily used by an old application. The application is hooked up to use the table CO for owners and cars. There also exists several other tables that use the CO table. I wish I could split the table into Owners and Cars, but the company doesn't want me to spend all my time doing it as there are several more features I need to add to the application.
Your thoughts on the Owners table are on the right track! Your problem is because your schema is not normalized. It's the fact you're storing two things (cars, and owners) in one table (your table CO).
You are correct that you should make an Owner table, but you should then remove the Owner information from the CO table entirely, and replace it with a foreign key to the Owners table.
So you want something like this:
CREATE TABLE Owner (
ownerID int not null primary key indentity(1,0),
FirstName varchar(255),
LastName varchar(255),
/* other fields here */
)
GO
CREATE TABLE Car
carID int not null primary key identity(1,0),
ownerID int not null references Owner(ownerID),
/* other fields go here */
GO
/* a convenience, read only view to replace your old CAR OWNER table */
CREATE VIEW Car_Owner AS
SELECT c.*, o.FirstName, o.LastName FROM Car c INNER JOIN Owner o ON c.ownerID = o.ownerID
Now, you have everything properly normalized in SQL. A view has given you back the car_owner as one thing in a pseudo-table.
But the real answer is, normalize your schema. Let SQL do what it does best (relate things to other things). Combining the two things on one table will just lead to more problems like you're encountering downstream.
Hopefully this answer seems helpful and not condescending, which is what I was going for! I have learned the hard way that this approach (normalize everything, let the database do some extra work to retrieve/display/insert it) is the only one that works out in the end.
You should create Owner table, Car table, OwnerCar table(if person can has a few cars). Owner table contains fields, that describe owner(owner properties)