Sql one to many relationship - sql

In my application I have the following Clients, Products. I want for each Client to have certain Products( one to many relationship) my code :
Tables Creation :
Create Table Client
(
IDC int identity(1,1) not null primary key,
NumeC nvarchar(50),
CIF nvarchar(50) unique
)
Create Table Produs
(
IDP int identity(1,1) not null,
NumeP nvarchar(50),
Cantitate int,
IDC int
)
this the Foreign Key :
Alter table Produs add constraint FK_Client_Produs_IDC
Foreign key (IDC) references Client(IDC)
Select statement Query to join Clients and foreach client to show Products :
Select NumeC,CIF from Client
Inner Join Produs
ON Client.IDC = Produs.IDC
I don't know what am I doing wrong, I just want to show Products for each client. It does not give me that. It just repeats the name of the client, now showing me The products for each client

In your SELECT you don't ever include anything from the Produs table, so why would it show it to you.
Select NumeC,CIF,NumeP
from Client
Inner Join Produs
ON Client.IDC = Produs.IDC

Related

Where is the mistake for this query logic?

I am working on some project and I have 8 tables I created tasks for my self for improving my knowledge and when I'm doing that I had a Problem during query
In below there is sample tables and data
CREATE TABLE Clients
(ID NUMBER(10),
name VARCHAR(30) NOT NULL,
surname VARCHAR(30) NOT NULL,
Cbudget NUMBER(10,2),
CompanyID NUMBER(10) NOT NULL,
PRIMARY KEY(ID));
Describe Clients
CREATE TABLE Contracts
(ID NUMBER(20),
ContractValue CHAR(255) NOT NULL,
CompanyID NUMBER(10) NOT NULL,
ClientID NUMBER(10) NOT NULL,
TransactionID NUMBER(10) NOt NULL,
PRIMARY KEY(ID));
Describe Contracts
ALTER TABLE Contracts ADD ClientID NUMBER
CREATE TABLE "Transaction"
(ID NUMBER(10),
Type NUMBER(1) NOT NULL,
Price NUMBER(10,2),
TDATE date,
ClientID NUMBER(10) NOT NULL,
PRIMARY KEY(ID));
Describe "Transaction"
here is the data
INSERT INTO Clients(ID,name,surname,Cbudget,CompanyID) VALUES (1,'hamza','bacara',98372.200,2);
INSERT INTO Clients(ID,name,surname,Cbudget,CompanyID) VALUES (2,'','bacara',87432.400,1);
INSERT INTO Clients(ID,name,surname,Cbudget,CompanyID) VALUES (3,'batikan','falay',213132.00,2);
INSERT INTO "Transaction"(ID,Type,Price,TDATE,ClientID)VALUES(1,'1',5000,current_date,2);
INSERT INTO "Transaction"(ID,Type,Price,TDATE,ClientID)VALUES(2,'1',6000,'11/09/2006',1);
INSERT INTO "Transaction"(ID,Type,Price,TDATE,ClientID)VALUES(3,'2',9000,current_date,3);
INSERT INTO Contracts(ID,ContractValue,CompanyID,ClientID,TransactionID)VALUES(1,'1 Million $',1,2,1);
INSERT INTO Contracts(ID,ContractValue,CompanyID,ClientID,TransactionID)VALUES(2,'50 Million $',2,1,2);
INSERT INTO Contracts(ID,ContractValue,CompanyID,ClientID,TransactionID)VALUES(3,'100 Million $',2,2,3);
and here is the query (it works but every time it just shows the data with '100 million $'
SELECT * FROM Contracts WHERE ClientID IN
(SELECT T.ClientID FROM "Transaction" T
INNER JOIN Contracts CT ON CT.TransactionID = CT.id WHERE CT.ContractValue = '1 Million $');
I have also constraints (I'm not sure it's important for you)
Actually, your query is giving the correct result as per your data. (Only one change in the query ...ON CT.TransactionID = CT.id WHERE... should be ...ON CT.TransactionID = T.id WHERE...)
In the CONTRACTS table, CLIENTID 2 is assigned to two contracts ID = 1 and 3. so the query is matching with two clients.
If you will update the CONTRACTS table as follows then it is giving the correct result.
UPDATE CONTRACTS
SET CLIENTID = 3
WHERE ID = 3
db fiddle demo

SQL Query that displays the number of athletes that have competed in at least ten different places(locations)

I'm building a query based on the fact that they have competed in ten or more places. Note that it does not matter how many sports or competitions they competed in, just how many places they have competed in.
CREATE TABLE Gender (
gender CHAR(1),
description VARCHAR(10),
PRIMARY KEY (gender));
CREATE TABLE People (
ID INT,
name VARCHAR(50),
gender CHAR(1),
height FLOAT,
PRIMARY KEY (ID),
FOREIGN KEY (gender) REFERENCES Gender (gender));
CREATE TABLE Sports (
ID INT,
name VARCHAR(50),
record FLOAT,
PRIMARY KEY (ID),
UNIQUE (name));
CREATE TABLE Competitions (
ID INT,
place VARCHAR(50),
held DATE,
PRIMARY KEY (ID));
CREATE TABLE Results (
peopleID INT NOT NULL,
competitionID INT NOT NULL,
sportID INT NOT NULL,
result FLOAT,
PRIMARY KEY (peopleID, competitionID, sportID),
FOREIGN KEY (peopleID) REFERENCES People (ID),
FOREIGN KEY (competitionID) REFERENCES Competitions (ID),
FOREIGN KEY (sportID) REFERENCES Sports (ID));
If anyone can help me with this it would be much appreciated!
As commented by Brad, you can use a simple aggregated query that JOINs table People with Results, with a HAVING BY clause to filter on the number of competitions each person participated to. It seems like you don’t need to bring in any other table to achieve your goal.
SELECT
p.ID,
p.Name
FROM
People p
Results r ON r.peopleID = p.ID
GROUP BY
p.ID,
p.Name
HAVING COUNT(*) >= 10

Creating a view in Sql with connected tables

I am trying to create a view off of two different tables. Basically I have 2 tables
(MatchStats- Holds all of the fixture information)
(Team - Holds all of the team information)
Here is the code for both tables
Team
CREATE TABLE TEAM
(
TeamID int NOT NULL,
TeamName varchar(30) NOT NULL,
Teamlocale varchar(30) NOT NULL,
CONSTRAINT pkTeamID PRIMARY KEY (TeamID),
)
MatchStats
CREATE TABLE MATCHSTATS
(
MatchStatsID int NOT NULL,
Team1ID int NOT NULL,
Team1Goals int NOT NULL,
Team2ID int NOT NULL,
Team2Goals int NOT NULL,
RefereeID int NOT NULL,
PitchID int NOT NULL,
sessionTime varchar(20) NOT NULL,
sessionDate varchar(20) NOT NULL,
CONSTRAINT pkMatchStatsID PRIMARY KEY (MatchStatsID),
CONSTRAINT fkTeam1ID FOREIGN KEY (Team1ID) REFERENCES TEAM(TeamID),
CONSTRAINT fkTeam2ID FOREIGN KEY (Team2ID) REFERENCES TEAM(TeamID),
CONSTRAINT fkReferee FOREIGN KEY (RefereeID) REFERENCES REFEREE(RefereeID),
CONSTRAINT fkpitchID FOREIGN KEY (PitchID) REFERENCES Pitch(pitchID),
)
I am trying to create a view that will display the fixture information but use the team name instead of ID. I have been researching and looking at previous questions online and I just cant seem to understand how to do it
This is what I have managed to come up with
CREATE VIEW FIXTUREHSITORY AS
SELECT m.Team1ID, m.Team1Goals, m.Team2ID, m.Team2Goals, T.TeamName
from MATCHSTATS as m
JOIN TEAM as t ON t.TeamID on
Overall I am trying to create a report that looks like this
Team 1 Name | Goals | Team 2 Name | Goals
Sorry if I seem vague and thanks in advance
A solution to your problem:
MSSQL
CREATE VIEW FIXTUREHISTORY AS
SELECT t1.TeamName Team1Name,
m.Team1Goals Team1Goals,
t2.TeamName Team2Name,
m.Team2Goals Team2Goals
from MATCHSTATS as m
INNER JOIN TEAM as t1 ON t1.TeamID = m.Team1ID
INNER JOIN TEAM as t2 ON t2.TeamID = m.Team1ID
Demo Link:
http://sqlfiddle.com/#!18/34883/1

SQL double primary key, many-to-many relationship

I'd like to connect 3 tables. In one of them I must use a compound primary key. I know, how to deal with single. I have the following tables to connect:
CREATE TABLE Med_list
(
ID_med_list INT IDENTITY(200001,1) ,
No_med_list INT,
ID_med INT REFERENCES Med(ID_med),
PRIMARY KEY(ID_med_list, No_med_list)
)
CREATE TABLE Med
(
ID_med INT IDENTITY(3001,1) PRIMARY KEY ,
Name VARCHAR(20)
)
CREATE TABLE Visit
(
ID_Visit INT IDENTITY(600001,1) PRIMARY KEY,
ID_patient INT REFERENCES Patients(ID_patient),
Visit_date Datetime,
ID_med_duty INT,
No_med_list INT
)
I would like to every patient could have more than one medicine during one visit. I don't know how to connect table Visit and Med_list the way acceptable to SQL Server.
Thank you in advance for every hint or help:)
You need a many to many relation, if Med_list is supposed to be this relation (medicine to visits) then you are only missing one foreign key that points to the visit so the tables relation looks like this
Patient. <--- Visit. <--- Med_list. ---> Meds
The tables like this:
CREATE TABLE Med_list
(
ID_med_list INT IDENTITY(200001,1) ,
No_med_list INT,
ID_med INT REFERENCES Med(ID_med),
ID_Visit INT REFERENCES Visit(ID_Visit)
PRIMARY KEY(ID_med_list, No_med_list)
)
CREATE TABLE Med
(
ID_med INT IDENTITY(3001,1) PRIMARY KEY ,
Name VARCHAR(20)
)
CREATE TABLE Visit
(
ID_Visit INT IDENTITY(600001,1) PRIMARY KEY,
ID_patient INT REFERENCES Patients(ID_patient),
Visit_date Datetime,
ID_med_duty INT,
No_med_list INT
)
And your query can look like this
Select * From patients p
Join Visit v on v.ID_Patient = p.ID_Patient
Join Med_list ml on ml.ID_Visit = v.ID_Visit
Join Med m on m.ID_med = ml.ID_med
You could try this
I am also new in many-to-many relationship query.
SQLFiddle Example
SELECT
P.name,
M.Name
FROM
med_list ML
LEFT JOIN med M ON m.ID_med=ML.ID_med
LEFT JOIN visit V ON V.ID_Visit=ML.ID_Visit
LEFT JOIN patients P ON P.ID_patient=V.ID_patient

How to select IDs from a table if two conditions in other tables match

I am developing a user feedback system using ASP.NET and C#. I have multiple tables and am trying to populate dropdown lists so that the feedback can be filtered.
My tables:
CREATE TABLE tblModules
(
Module_ID nvarchar(10) PRIMARY KEY,
Module_Title nvarchar(MAX) NOT NULL
);
CREATE TABLE tblQuestions
(
Q_ID int PRIMARY KEY IDENTITY(1,1),
Question_Text varchar(1000) NOT NULL
);
CREATE TABLE tblFeedback
(
Submission_ID int PRIMARY KEY IDENTITY(1,1),
Username varchar(100) NOT NULL,
Domain varchar(50) NOT NULL,
DateTime_Submitted datetime NOT NULL
Module_ID nvarchar(10)
FOREIGN KEY (Module_ID) REFERENCES tblModules (Module_ID);
);
CREATE TABLE tblAnswers
(
Q_ID int NOT NULL,
Submission_ID int NOT NULL,
Answer_Text varchar(max),
FOREIGN KEY (Q_ID) REFERENCES tblQuestions(Q_ID),
FOREIGN KEY (Submission_ID) REFERENCES tblFeedback(Submission_ID)
);
I have two dropdown lists. First one is populated with all modules from a table. The second needs to be populated with Questions from tblQuestions but only if any answers to it exist (therefore if the Question ID 'Q_ID' exists in tblAnswers).
I can get the selectedModuleID from the first dropdown list. I have a List of all Questions referenced by Q_ID in tblAnswers. How do I crossreference this list with the module ID?
Each feedback submission gets a Submission ID and Module ID.
You want:
questions that have answers
questions that have a module parent (via tblfeedback)
So, my guess at what you want:
SELECT
*
FROM
tblQuestions Q
WHERE
EXISTS (SELECT *
FROM
tblAnswers A
JOIN
tblFeedback F ON A.Submission_ID = F.Submission_ID
WHERE
Q.Q_ID = A.Q_ID AND F.Module_ID = #moduleID)
This should do the trick...
SELECT Q_ID, Question_Text tblQuestions a
WHERE EXISTS (SELECT NULL FROM tblAnswers a WHERE a.Q_ID = q.Q_ID)