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
Related
I want to add the results of a query into a table. There are multiple values, being inserted into multiple rows that are currently NULLS.
I have the following tables:
CREATE TABLE CAR (
CarID INT NOT NULL PRIMARY KEY,
Make VARCHAR (30) NOT NULL,
Model VARCHAR (30) NOT NULL,
Type VARCHAR (30) NOT NULL,
YearModel INT NOT NULL,
Price VARCHAR (100) NOT NULL,
);
CREATE TABLE [TRANSACTION] (
tID INT NOT NULL PRIMARY KEY,
cID INT NOT NULL FOREIGN KEY REFERENCES CUSTOMER(CID),
CarID INT NOT NULL FOREIGN KEY REFERENCES CAR(CARID),
eID INT NOT NULL FOREIGN KEY REFERENCES EMPLOYEE(EID),
tDate DATE,
PickupDate DATE NOT NULL,
ReturnDate DATE NOT NULL
);
I then had to add a new column:
ALTER TABLE [TRANSACTION]
ADD Amount_Due int;
The following code gives me the results I need:
SELECT Price*DATEDIFF(DAY,PickupDate, ReturnDate)
FROM [TRANSACTION], CAR
WHERE [TRANSACTION].CarID = CAR.CarID
But I don't know how to insert all of the data into my Amount_Due column.
I have tried to use INSERT INTO, but it's telling me I have a syntax error near Amount_Due.
INSERT INTO [TRANSACTION] Amount_Due
SELECT Price*DATEDIFF(DAY,PickupDate, ReturnDate)
FROM CAR, [TRANSACTION]
WHERE CAR.CarID = [TRANSACTION].CarID
I have played around with INSERT INTO and UPDATE and I cannot wrap my head around what I'm doing wrong, or what I am missing.
I'm using SQL SMS 2018
Thank you for any help.
You are not inserting data you are updating existing rows, so you need to update:
update t set
t.Amount_Due = c.Price * DateDiff(day, c.PickupDate, c.ReturnDate)
from [transaction] t
join car c on c.carId=t.carId
Notes
Always use proper join syntax, avoid adding tables separated by
commas.
Also always alias your tables with meaningful short
aliases for readability.
Avoid using reserved words for objects eg
transaction - if your table contains more than 1 row then call it
transactions and avoid the need to always have to use [] to avoid
ambiguity.
SSMS is not SQL Server, SSMS is just an application used to access SQL Server. Use select ##version if you ever need to know your SQL Server version.
This question already has answers here:
Creating table via SQL Command Line, invalid identifier
(3 answers)
Closed 3 years ago.
Image of the code with table, query and error
I have oracle 10g installed on my computer. I have created a table in it named STUDENT and this STUDENT table has a primary key called RNO and now I want to create another table named FEE and make this RNO key into a foreign key in FEE table with the following query:
CREATE TABLE FEE ( RNO NUMBER(2), Amount number(20) Not Null, Date varchar2(10) Not Null, Receipt Number(10) Not Null, CONSTRAINT FEEFK FOREIGN KEY (RNO) REFERENCES STUDENT (RNO));
Now I have done all I could to correct it but just can't seem to find any problem or error with this query above. The Query gives the following error in Oracle 10g:
ORA-00904: : invalid identifier
Column name can't be DATE, it is reserved for datatype. Rename it to, say, CDATE.
SQL> CREATE TABLE student (rno NUMBER (2) PRIMARY KEY);
Table created.
SQL> CREATE TABLE FEE
2 (
3 RNO NUMBER (2),
4 Amount NUMBER (20) NOT NULL,
5 cDate VARCHAR2 (10) NOT NULL,
6 Receipt NUMBER (10) NOT NULL,
7 CONSTRAINT FEEFK FOREIGN KEY (RNO) REFERENCES STUDENT (RNO)
8 );
Table created.
SQL>
Use double qoutes "Date" or rename your column Date as some other name like DateColumn as Date is a reserved name fpr date types in oracle
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.
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;
I am new to php and sql and I am building a little game to learn a little bit more of the latter.
This is my simple database of three tables:
-- *********** SIMPLE MONSTERS DATABASE
CREATE TABLE monsters (
monster_id VARCHAR(20),
haunt_spawn_point VARCHAR(5) NOT NULL,
monster_name VARCHAR(30) NOT NULL,
level_str VARCHAR(10) NOT NULL,
creation_date DATE NOT NULL,
CONSTRAINT monster_id_pk PRIMARY KEY (monster_id)
);
-- ****************************************
CREATE TABLE spawntypes (
spawn_point VARCHAR(5),
special_tresures VARCHAR (5) NOT NULL,
maximum_monsters NUMBER NOT NULL,
unitary_experience NUMBER NOT NULL,
CONSTRAINT spawn_point_pk PRIMARY KEY (spawn_point)
);
-- ****************************************
CREATE TABLE fights (
fight_id NUMBER,
my_monster_id VARCHAR(20),
foe_spawn_point VARCHAR(5),
foe_monster_id VARCHAR(20) NOT NULL,
fight_start TIMESTAMP NOT NULL,
fight_end TIMESTAMP NOT NULL,
total_experience NUMBER NOT NULL
loot_type NUMBER NOT NULL,
CONSTRAINT my_monster_id_fk FOREIGN KEY (my_monster_id)
REFERENCES monsters (monster_id),
CONSTRAINT foe_spawn_point_fk FOREIGN KEY (foe_spawn_point)
REFERENCES spawntypes (spawn_point),
CONSTRAINT fight_id_pk PRIMARY KEY (fight_id)
);
Given this data how can I easily carry out this two tasks:
1) I would like to create a pl/sql function that passing only a fight_id as a parameter and given the foe_spawn_point (inside the fight table) return the unitary_experience that is related to this spawn point referencing the spawntypes table, how can I do it? :-/ [f(x)]
In order to calculate the total experience earned from a fight (unitary_experience * fight_length) I have created a function that given a particular fight will subtract the fight_end with the fight_start so now I know how long the fight lasted. [f(y)]
2) is it possible to use this two functions (multiply the result that they returns) during the database population task?
INSERT INTO fights VALUES(.... , f(x) * f(y), 'loot A');
in order to populate all the total_experience entries inside the fights table?
thank you for your help
In SQL, you don't generally talk about building functions to do things. The building blocks of SQL are queries, views, and stored procedures (most SQL dialects do have functions, but that is not the place to start).
So, given a variable with $FIGHTID you would fetch the unitary experience with a simple query that uses the join operation:
select unitary_experience
from fight f join
spawnTypes st
on st.spawn_point = f.foe_spawn_point
where fightid = $FIGHTID
If you have a series of values to insert, along with a function, I would recommend using the select form of insert:
insert into fights(<list of columns, total_experience)
select <list of values>,
($FIGHT_END - $FIGHT_START) * (select unitary_experience from spawnTypes where spawnType ='$SPAWN_POINT)
One comment about the tables. It is a good idea for all the ids in the table to be integers that are auto-incremented. In Oracle you do this by creating a sequence (and it is simpler in most other databases).