Selecting data from a database via a joined table - sql

I'm currently making a website that is used to advertise car sharing for festivals. I need to list all trips which are currently assigned to a user but seeing as the database relationship would be many to many I have had to make a client_trip table.
My question:
How would I select trips from the trip table based on the information in my client_trip table?
I'm currently using PostgreSQL and Java servlets. Thanks very much for any help. :)
CREATE TABLE users
(
user_id SERIAL,
user_username VARCHAR (20),
user_firstname VARCHAR(20),
user_surname VARCHAR(20),
user_password VARCHAR(50),
user_email VARCHAR(100),
user_role VARCHAR(20),
PRIMARY KEY(user_id)
);
CREATE TABLE trips
(
trip_id SERIAL,
trip_name VARCHAR (100),
trip_user_username VARCHAR (50),
trip_festival_id SERIAL REFERENCES festivals(festival_id),
trip_festival_name VARCHAR(100),
trip_depart_date DATE,
trip_return_date DATE,
trip_spaces INT,
trip_cost Decimal (19,2),
trip_desc VARCHAR,
PRIMARY KEY(trip_id)
);

how would I select trips from the trip table based on the information in my client_trip
With a given user_id:
SELECT t.*
FROM trips t
JOIN client_trip ct USING (trip_id)
WHERE ct.user_id = ??

Related

Invalid table name error when creating a table

Very new to SQL, but I thought that I had at least mastered how to make tables. I am trying to create the following table and get the error 'ORA-00903: invalid table name'. I'm not sure what is wrong.
Create table order (
order_id int,
item_type varchar(50),
item_name varchar(50),
item_price decimal(10,2),
primary key(order_id)
);
I am testing this on Oralce Live SQL and it is ok as well as on my Oracle 12c Database EE, all you need to add are "". But even so, I would not recommend it to use reserved words for naming tables.
Create table "order" (
order_id int,
item_type varchar(50),
item_name varchar(50),
item_price decimal(10,2),
primary key(order_id)
);
insert into "order" values (1, 'Item', 'Name', '20.2');
select * from "order";

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.

Work-built custom vending machine SQL assistance

At work, we have build a vending machine and i have been asked as a side-project to attempt to create a SQL database for it. It will not be used with the vending machine, but will be used for me to practise as i'm very new to SQL (1 month in).
The vending machine will use a keyfob to touch on. Once that's done, you open up the door and grab what you like. The machine has weight sensors, so whatever you take will be added to your fob amount.
Below is what i have produced. I am currently only creating the tables. Please send me your constructive critisism and corrections as it will help me greatly!
CREATE TABLE Vender (
Name varchar (50),
Description varchar (50)
);
CREATE TABLE Bay (
StockItem uniqueidentifier,
Channel integer
);
CREATE TABLE Users (
NameFirst varchar (50),
NameLast varchar (50),
Title varchar (50),
FobID uniqueidentifier,
Credential_TakeStock integer,
Credential_Addstock integer,
Credential_Admin integer
);
CREATE TABLE Reasons (
Name uniqueidentifier
);
CREATE TABLE Machine (
Name uniqueidentifier
);
CREATE TABLE StockItems (
Code integer,
Description varchar (50),
Vendor varchar (50),
LeadTime time,
QtyCurrent integer,
QtyMax integer,
QtyMin integer,
QtyCritical integer,
WeightInGrams integer,
Bay ???
);
CREATE TABLE Purchase (
DateTime datetime,
UserName varchar,
StockItem uniqueidentifier,
Reason varchar,
Machine uniqueidentifier,
Qty integer,
DepletedItemReturned bit
);
One thing to also mention is i'm not sure of the data value for Bay in StockItems.
Thank you in advance.

Creating table when each object may have a list of values

First I've created a table with information on stores and transactions with the following query:
CREATE TABLE main.store_transactions
(
store_id varchar(100) NOT NULL,
store_name varchar(100),
store_transaction_id varchar(100),
transaction_name varchar(100),
transaction_date timestamp,
transaction_info varchar(200),
primary_key(store_id)
)
But then I realized that the same store may have various transactions related to it, not just one. How should I implement table creation in this case?
One thing that comes to mind is to create a separate table with transactions, each transaction having store_id as a foreign key. And then just join when needed.
How is it possible to implement it in a single table?
Well, the most elegant way would be indeed to create a satelite table for your stores and reference it to the store_transactions table, e.g:
CREATE TABLE stores
(
store_id varchar(100) NOT NULL PRIMARY KEY,
store_name varchar(100)
);
CREATE TABLE store_transactions
(
store_id varchar(100) NOT NULL REFERENCES stores(store_id),
store_transaction_id varchar(100),
transaction_name varchar(100),
transaction_date timestamp,
transaction_info varchar(200)
);
With this structure you will have many transactions to a single store.
There are other less appealing options, such as customizing a data type for stores and creating an array of it in the table store_transactions. But regarding the costly maintainability of such approach, I would definitely discourage it.

Enforcing referential integrity from one table to any table

I have a variety of tables that represent business objects, e.g. Products, People, Locations and I'm wanting to add a Tags table (as in taxonomy).
CREATE TABLE Tags (
tagId bigint IDENTITY,
name nvarchar(50)
)
How can I allow multiple tags to be applied to multiple types of entities in a way that allows the DBMS to enforce referential integrity without needing a linking table like this:
CREATE TABLE TagUse (
tagId bigint,
productId bigint NULL,
personId bigint NULL,
locationId bigint NULL,
...
whateverId bigint NULL
)
Or worse:
CREATE TABLE PersonTags (
tagId bigint,
personId bigint
)
CREATE TABLE LocationTags (
tagId bigint,
locationId bigint
)
...
CREATE TABLE WhateverTags (
tagId bigint,
whateverId bigint
)
I just thought of a third option: rather than having separate *Tags tables for each entity, each entity can be thought of inheriting from "Taggable" which is then referenced-to by the child tables:
CREATE TABLE Taggable (
taggableId bigint,
tagId bigint
)
CREATE TABLE Persons (
personId bigint,
...
taggableId bigint
)
You could use a sequence object:
CREATE TABLE [TaggableObjects] (
objectId BIGINT IDENTITY(1,1)
)
CREATE TABLE [Persons] (
objectId BIGINT, -- referencing Objects.objectId
name VARCHAR(50)
)
CREATE TABLE [Locations] (
objectId BIGINT, -- referencing Objects.objectId
country VARCHAR(50)
)
In programming languages like Java and C# you'd call Persons and Locations an extension of TaggableObject.
Following this you could implement the Tags as:
CREATE TABLE [Tags] (
tagId BIGINT IDENTITY(1,1),
objectId BIGINT
)
Though the problem with an implementation like this one would be that you have to figure out the best way to identify of what type Tags.objectId is.
Note that depending on which engine you'll be using, many support some sort of functionality to more easily implement a sequence object, you might want to right up on it.