invalid identifier when executing select in oracle - sql

I am trying to execute a select in oracle that uses 3 tables, nba_player, nba_team, and nba_team_roster. nba_player includes player data with a player_id and nba_team includes team information with a team_id. nba_team_roster is an associative entity and includes a player_id and team_id to associate the two. I want this query to return the first and last name of each player on team 'OKC' but for some reason it gives me the error below. I am not sure why this isn't executing properly. Any help would be greatly appreciated.
select nba_player.first_name, nba_player.last_name
from nba_player,nba_team
join nba_team_roster
on nba_team_roster.player_id=nba_player.player_id
where nba_team_roster.team_id= nba_team.team_id
and nba_team.team_name='OKC';
on nba_player.player_id=nba_team_roster.player_id
*
ERROR at line 4:
ORA-00904: "NBA_PLAYER"."PLAYER_ID": invalid identifier
CREATE TABLE NBA_Team(
team_id number primary key,
team_name varchar(5)
);
CREATE TABLE NBA_Player(
player_id number primary key,
first_name varchar(10),
last_name varchar (11),
position varchar(3),
salary number,
points_per_game number
);
CREATE TABLE NBA_Team_Roster(
roster_ID number primary key,
team_id number,
player_id number unique,
foreign key (team_id) references NBA_Team(team_id),
foreign key (player_id) references NBA_Player(player_id)
);

Simple rule: Never use commas in the FROM clause. Always use proper, explicit JOIN syntax. That will solve your problem and make the query easier to understand:
select p.first_name, p.last_name
from nba_player p join
nba_team_roster r
on r.player_id = p.player_id join
nba_team t
on r.team_id = t.team_id
where t.team_name = 'OKC';
Note that I also introduced table aliases. These make the query easier to write and to read.

Related

In a SELECT command, how do I use data from one table to specify data in another?

I have 2 tables. What is important is the PlayerId and the Username.
CREATE TABLE [dbo].[Run]
(
[RunId] INT NOT NULL,
[PlayerId] INT NOT NULL,
[Duration] TIME(7) NOT NULL,
[DateUploaded] NCHAR(10) NOT NULL,
[VersionId] INT NOT NULL,
PRIMARY KEY CLUSTERED ([RunId] ASC),
CONSTRAINT [FK_Run_Player]
FOREIGN KEY ([PlayerId]) REFERENCES [dbo].[Player] ([PlayerId]),
CONSTRAINT [FK_Run_Version]
FOREIGN KEY ([VersionId]) REFERENCES [dbo].[Version] ([VersionId])
);
CREATE TABLE [dbo].[Player]
(
[PlayerId] INT NOT NULL,
[Username] NCHAR(20) NOT NULL,
[ProfilePicture] IMAGE NULL,
[Country] NCHAR(20) NOT NULL,
[LeagueId] INT NULL,
[DateJoined] DATE NULL,
PRIMARY KEY CLUSTERED ([PlayerId] ASC),
CONSTRAINT [FK_Player_League]
FOREIGN KEY ([LeagueId]) REFERENCES [dbo].[League] ([LeagueId])
);
I have a select command:
SELECT
PlayerId, Duration, VersionId, DateUploaded
FROM
[Run]
(with apologies in advance for my messy made up pseudocode), what I need it to do is:
SELECT (Player.PlayerId.Username)
What I basically need it to do, is instead of giving me just PlayerId, I need it to get the corresponding Username (from the other table) that matches each PlayerId (PlayerId is a foreign key)
So say for example instead of returning
1, 2, 3, 4, 5
it should return
John12, Abby2003, amy_932, asha7494, luke_ww
assuming, for example, Abby2003's PlayerId was 2.
I've done trial and error and either nobody's tried this before or I'm searching the wrong keywords. This is using VS 2022, ASP.NET Web Forms, and Visual Basic, but that shouldn't affect anything I don't think. Any syntax ideas or help would be greatly appreciated.
try this for join the 2 Table togother
SELECT R.RunId
,R.PlayerId
,R.Duration
,R.DateUploaded
,R.VersionId
,P.Username
,P.ProfilePicture
,P.Country
,P.LeagueId
,P.DateJoined
FROM Run R
inner join Player P on R.PlayerId = P.PlayerId
Usually in this case joins are used. You can join the two tables together, give them aliases (or don't, personal preference really), then select what you need. In this case, you would probably want an inner join. Your query would probably look something like this:
SELECT p.Username FROM [Run] r
INNER JOIN [Player] p ON r.PlayerId = p.PlayerId
Then if you need to you can put a WHERE clause after that.
More about joins here

I have a problem with the grouping for this query

I have a problem grouping a 4 join table.
Due to new government regulations, every private service vehicle must be periodically serviced and have proper training, RideWiki is required to report to the government with proof that each driver has the required documents to be eligible to be a private service driver.
List the drivers that have serviced their car within the last two months (After 16/4/2019)
and have had done their basic driver training.
Carservice>>Driver<
select Dname
from driver,carservice,dsession,training;
where driver.dnric = carservice.dnric
and driver.dnric = dsession.dnric
and dsession.tid = training.tid
where sysdate-servicedate < 60
group by dnric,tid,dname;
CREATE TABLE DRIVER
(
DNRIC CHAR(12) PRIMARY KEY,
DGrade CHAR(1),
DLicense NUMBER(8),
DStart DATE,
DIPlan CHAR(1),
DName VARCHAR(20),
DDOB DATE,
DGENDER CHAR(1),
DMOBILE NUMBER(11)
);
CREATE TABLE CARSERVICE
(
DCarID NUMBER(6) PRIMARY KEY,
CarType VARCHAR(20),
ServRem VARCHAR(250),
DNRIC CHAR(12),
CarServ CHAR(1),
FOREIGN KEY (DNRIC) references DRIVER(DNRIC)
);
CREATE TABLE DSESSION
(
SID NUMBER(7) PRIMARY KEY,
SDate DATE,
DNRIC CHAR(12),
TID NUMBER(6),
FOREIGN KEY (DNRIC) references DRIVER(DNRIC),
FOREIGN KEY (TID) references TRAINING(TID)
);
CREATE TABLE TRAINING
(
TID NUMBER(6) PRIMARY KEY,
TrainingPrg VARCHAR(50),
PrgSession VARCHAR2(10)
);
You referenced a wrong column name in servicedate where you mentioned as sdate while creating a table.
SELECT DISTINCT Dname
FROM driver d
INNER JOIN carservice car ON d.dnric = car.dnric
INNER JOIN dsession dses ON d.dnric = dses.dnric
INNER JOIN training train ON dses.tid = train.tid
WHERE sysdate-dses.sdate < 60
Few good practices to keep in mind:
Using table aliases d,car,dses,train of your choice to access data.
Use ANSI syntax (JOIN statements) rather than your alternate syntax for better readability of code.
Don't miss any syntax errors to hide your way.
Also, you should mention constraint variable properly if using ORACLE / SQL Server / MS Access
CONSTRAINT FK_DNRIC FOREIGN KEY (DNRIC) references DRIVER(DNRIC),
Hope this helps.
You have a wrong semicolon at the end of the from row.
Also, you have not used an aggregation function so you shoud not use group by.
Use distinct if you need to not repeat values.
select distinct Dname
from driver
INNER JOIN carservice ON driver.dnric = carservice.dnric
INNER JOIN dsession ON driver.dnric = dsession.dnric
INNER JOIN training ON dsession.tid = training.tid
Where sysdate-servicedate < 60
You should use the explict join syntax and avoid the old (from 1992) implicit join syntax based on the where clause.
Thanks alot guys!! I had alot of help just with querying with INNER JOIN.

SQL Join - Query error

So I would like to display the most experience player, at first I was going to display all players and experiencepoints then try and only display the max. so heres the code for both tables and the query itself
CREATE TABLE Player
(
Player_ID INTEGER CONSTRAINT pk_player PRIMARY KEY,
Pname VARCHAR(60),
DOB VARCHAR(10),
Heightcm NUMBER(10),
Weightkg NUMBER(10),
Position VARCHAR(20),
Team_ID INTEGER CONSTRAINT fk_player REFERENCES Team(Team_ID)
)
CREATE TABLE PlayerCareer_Performance
(
Player_Performance_ID INTEGER CONSTRAINT pk_PP PRIMARY KEY,
Player_ID INTEGER,
total_points NUMBER(10),
total_fouls NUMBER(10),
ExperiencePoints NUMBER(10),
CONSTRAINT fk_Pp FOREIGN KEY (Player_ID) REFERENCES Player(Player_ID)
)
Thats the table code, below is the query:
SELECT PLAYER.PLAYER_ID,PLAYER.PNAME,PLAYERCAREER_PERFORMANCE.EXPERIENCEPOINTS
FROM PLAYER
JOIN PLAYERCAREER_PERFOMANCE
ON PLAYERPERFROMANCE.PLAYER_ID = PLAYER.PLAYER_ID;
Player is underlined on yellow and it says "Is disconnected from the rest of join graph"
Any ideas, anyone? I cant see a fix for it :(
At first sight, you are joining the table PLAYERCAREER_PERFORMANCE but joining on a field of table called PLAYERPERFROMANCE (sic). Is that a typo?
This:
SELECT Player.Player_ID, Player.Pname, PlayerCareer_Performance.ExperiencePoints
FROM Player
JOIN PlayerCareer_Performance
ON PlayerCareer_Performance.Player_ID = Player.Player_ID
Seems to work fine (just corrected the typo): check it at sqlfiddle.
As a general suggestion, keep your code consistent... you are using different column formats (e.g.: ExperiencePoints vs total_points), and are putting all SQL query code in caps, which just makes it difficult to read and find typos
Use an inner join (updated to reflect popular demand):
select p.player_id, p.pname, pcp.experiencepoiuts
from Player p
inner join PlayerCareer_Performance pcp on pcp.player_id = p.player_id

How can I get this query to print a record that only exists in one table?

I am trying to create a query that will accept a date from the user and display information from two tables based on this date. This works for all of my tests except my last test. My last test, I enter a date that should return a record that only exists in the expmast table and does not exist in the expbycc table. When I enter the date to try and get this record to be returned, it tells me no records have been found. I know this is because in my where, i have an AND that checks if M.ExpNum = C.ExpNUm which isn;t true for this record because it only exists in one table. I can not figure out how to get this query to work. Any help/advice is greatly appreciated. Below is my script, followed by the table structures used for this query, thank you.
Script:
ACCEPT Date PROMPT 'Enter a date:';
SELECT M.ExpNum, EDate, IsCash, StoreCode, CashAmt, CType, CCNum, Amt
FROM ExpMast M, ExpByCc C
WHERE EDate = to_date('&Date','mm-dd-yy')
AND M.ExpNum = C.ExpNum;
Tables:
CREATE TABLE EXPMAST
(ExpNum NUMBER(2,0) NOT NULL PRIMARY KEY,
EDate DATE,
IsCash VARCHAR2(1),
StoreCode VARCHAR2(4),
CONSTRAINT fk_STORE_EXPMAST FOREIGN KEY (StoreCode)
REFERENCES STORE (Code)
);
CREATE TABLE ExpByCC
(ExpNum NUMBER(2,0) NOT NULL,
CType VARCHAR2(1) NOT NULL,
CCNum VARCHAR2(16) NOT NULL,
Amt DECIMAL(5,2),
CONSTRAINT fk_CRCARD_ExpByCC FOREIGN KEY (CType, CCNum)
REFERENCES CRCARD (CType, CCNum),
CONSTRAINT fk_EXPMAST_ExpByCC FOREIGN KEY (ExpNum)
REFERENCES EXPMAST (ExpNum),
CONSTRAINT pk_ExpByCC PRIMARY KEY (ExpNum, CType, CCNum)
);
You need a left outer join. And you can't express an outer join using your implicit join syntax. You want to use explicit joins in the from clause.
A simple rule: NEVER use commas in the from clause.
Now, it is easy:
SELECT M.ExpNum, EDate, IsCash, StoreCode, CashAmt, CType, CCNum, Amt
FROM ExpMast M LEFT OUTER JOIN
ExpByCc C
ON M.ExpNum = C.ExpNum AND
WHERE M.EDate = to_date('&Date','mm-dd-yy') AND
C.ExpNum IS NULL;

ORA-00918: column ambiguously defined [duplicate]

This question already has an answer here:
ORA 00918- Column ambiguosly defined error [duplicate]
(1 answer)
Closed 9 years ago.
I am trying to retrieve some data (coursename) from one of my tables but the following error is coming all the time
ORA-00918: column ambiguously defined
the command I am typing is:
select bookno,courno,coursename
from booking, course,coursename
where bookno = 6200
and booking.courno = course.courno
and coursename.coursenameno = course.coursenameno
I have some tables as described :
CREATE TABLE BOOKING
(BOOKNO NUMBER (4) NOT NULL,
COURNO NUMBER (4) NOT NULL,
BOOKDATE DATE,
BOOKCUSTPAYMENT VARCHAR (20),
CONSTRAINT PK_BOOK PRIMARY KEY (BOOKNO,COURNO),
CONSTRAINT FK_BOOK FOREIGN KEY (COURNO) REFERENCES COURSE(COURNO)
ON DELETE CASCADE);
CREATE TABLE CUSTOMER
(CUSTNO NUMBER (4) NOT NULL, -- creation of primary-key
PROFNO NUMBER (4) NOT NULL,
CUSTFNAME VARCHAR (15),
CUSTLNAME VARCHAR (15),
CUSTDOB DATE,
CUSTPHONEDAY NUMBER (15),
CUSTPHONEEVE NUMBER (15),
CONSTRAINT PK_CUST PRIMARY KEY (CUSTNO),
CONSTRAINT FK_PROF FOREIGN KEY (PROFNO) REFERENCES PROFICIENCY(PROFNO)
ON DELETE CASCADE);
CREATE TABLE COURSENAME
( COURSENAMENO NUMBER (4) NOT NULL,
COURSENAME VARCHAR (20),
COURSEDESC VARCHAR (120),
COURSEDAYCOST NUMBER (7,2),
CONSTRAINT PK_COURSENAME PRIMARY KEY (COURSENAMENO));
CREATE TABLE COURSE
(COURNO NUMBER (4) NOT NULL, -- creation of primary-key
COURSTART DATE,
COUREND DATE,
COURSENAMENO NUMBER (4) NOT NULL,
ACCDAYNO NUMBER (4) NOT NULL,
FOODNO NUMBER (4) NOT NULL,
TRANSNO NUMBER (4) NOT NULL,
CONSTRAINT PK_COURSE PRIMARY KEY (COURNO),
CONSTRAINT FK_COURSENAME FOREIGN KEY (COURSENAMENO) REFERENCES COURSENAME(COURSENAMENO));
I am researching but I cannot figure out what is happening !!!
when the same column appears in several tables you need to specify which table is the one to be used. As a general rulem its always a good idea to prefix the column with the table (or alias) as improves readability and speeds up parsing.
so, for your query try (changes in upper case)
select BOOKING.bookno,BOOKING.courno,COURSENAME.coursename
from booking, course,coursename
where BOOKING.bookno = 6200
and booking.courno = course.courno
and coursename.coursenameno = course.coursenameno
You need to specify from which table the columns in SELECT and WHERE statements should be retrieved:
select booking.bookno, booking.courno, course.coursename
from booking, course, coursename
where booking.bookno = 6200
and booking.courno = course.courno
and coursename.coursenameno = course.coursenameno
Also, consider using ANSI SQL-92+ JOIN syntax like so:
select booking.bookno, booking.courno, course.coursename
from booking
inner join course on booking.courno = course.courno
inner join coursename on coursename.coursenameno = course.coursenameno
where booking.bookno = 6200
See [Bad habits to kick : using old-style JOINs][1] for some reasoning about it.
[1]: https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins
When a column is ambigious, this means the database doesnt know which column to use from 2 or more different tables.
You must define in the select like this
select tablename.bookno,tablename.courno,tablename.coursename
from booking, course,coursename
where tablename.bookno = 6200
and booking.courno = course.courno <-- Here its correct
and coursename.coursenameno = course.coursenameno <-- Here its correct
Change tablename. to the correct table where the column is.
field courno in your select: you haven't defined from which table: course or booking