Join 3 Tables DB - sql

I have 3 tables: CUSTOMERS, REGISTRATION and TUITION table.
The Registration table has foreign key:
ID_CLIENTES (FK)
ID_AULAS (FK)
And primary key:
ID_INSCRICAO
The objective is to create a select, but which has all the tables according to the inscriptions ie (table.attribute):
INSCRICAO.ID_INSCRICAO | INSCRICAO.DATA | CLIENTES.CNOME | AULAS.ANOME | AULAS.DATA | AULAS.VAGAS |
Have tried using the model:
SELECT INSCRICAO.ID_INSCRICAO,
INSCRICAO.DATA,
CLIENTES.CNOME,
AULAS.ANOME,
AULAS.DATA,
AULAS.VAGAS
FROM table1 INSCRICAO
left outer join table2 CLIENTES
on INSCRICAO.ID_INSCRICAO=CLIENTES.ID_CLIENTES
left outer join table3 AULAS
on AULAS.ID_AULA = INSCRICAO.ID_INSCRICAO;
That gives me error or multiplies the rows of tables, and the goal was to have the same number of records that the table entries
Can anyone help?

Related

SQL to concatenate two columns and join two tables

Table person:
| id | f_name | l_name |
Table sales:
| id | amount | date | itemname |
I have a problem joining the two tables which concat f_name and last_name as fullname column, and joining with table sales. Here id is same on both tables.
Output:
| itemname| date |fullname |
What I have tried:
select *
from
(select
concat(f_name, l_name) as fullname
from
tblperson) p
left join
select itemname, date
from table sales s on s.id = p.id
It should actually be
SELECT table_sales.*, concat(table_person.f_name, table_person.l_name) as fullname
FROM table_person
LEFT JOIN table_sales
ON table_person.id = table_sales.id
have not tested this but that is the syntax
you're missing a field like person_id in your sales table (which references the id field in the person table). You can then use a join to properly join the data together.
You are so close. Try this
select p.*,concat(f_name,l_name)as fullname, s.itemname,s.date, s.amount
from person p left join
sales s on s.id=p.id
Here ia good read on sql join.
https://www.w3schools.com/sql/sql_join.asp

Postgres join and count multiple relational tables

I want to join the 2 tables to the first table and group by a vendor name. I have three tables listed below.
Vendors Table
| id | name
|:-----------|------------:|
| test-id | Vendor Name |
VendorOrders Table
| id | VendorId | Details | isActive(Boolean)| price |
|:-----------|------------:|:------------:| -----------------| --------
| random-id | test-id | Sample test | TRUE | 5000
OrdersIssues Table
| id | VendorOrderId| Details. |
|:-----------|--------------:-----------:|
| order-id | random-id | Sample test|
The expected output is to count how many orders belong to a vendor and how many issues belongs to a vendor order.
I have the below code but it's not giving the right output.
SELECT "vendors"."name" as "vendorName",
COUNT("vendorOrders".id) as allOrders,
COUNT("orderIssues".id) as allIssues
FROM "vendors"
LEFT OUTER JOIN "vendorOrders" ON "vendors".id = "vendorOrders"."vendorId"
LEFT OUTER JOIN "orderIssues" ON "orderIssues"."vendorOrderId" = "vendorOrders"."id"
GROUP BY "vendors".id;```
You need the keyword DISTINCT, at least for allOrders:
SELECT v.name vendorName,
COUNT(DISTINCT vo.id) allOrders,
COUNT(DISTINCT oi.id) allIssues
FROM vendors v
LEFT OUTER JOIN vendorOrders vo ON v.id = vo.vendorId
LEFT OUTER JOIN orderIssues oi ON oi.vendorOrderId = vo.id
GROUP BY v.id, v.name;
Consider using aliases instead of full table names to make the code shorter and more readable.
You are joining along two related dimensions. The overall number of rows is the number of issues. But to get the number of orders, you need a distinct count:
SELECT v.*, count(distinct vo.id) as num_orders,
COUNT(oi.vendororderid) as num_issues
FROM vendors v LEFT JOIN
vendorOrders vo
ON v.id = vo.vendorId LEFT JOIN
orderIssues oi
ON oi.vendorOrderId = vo.id
GROUP BY v.id;
Notes:
Table aliases make the query easier to write and to read.
Quoting column and table names makes the query harder to write and read. Don't quote identifiers (you may need to recreate the tables).
Postgres support SELECT v.* . . . GROUP BY v.id assuming that the id is the primary key (actually, it only needs to be unique). This seems like a reasonable assumption.

What happens to view table when a new row is inserted?

Let's say I have 3 tables:
Products (BarCode[PK], PName, Price, QuantityInStock)
Saless (SaleID[PK], DeliveryAddress, CreditCard)
SaleItems (SaleID[PFK], BarCode[PFK], Quantity)
and then I create a view table called allproductsales:
create view allproductsales
as
select
s.saleid, p.barcode, p.pname
from
products p
left join
SALEITEMS si ON si.BARCODE = p.BARCODE
left join
saless s ON si.SALEID = s.SALEID;
and then I decide to insert new row into products like
INSERT INTO PRODUCTS
VALUES (3545322, 'Carrot', 0.10, 34);
and when I get display everything from allproductsales I can see newly inserted row there without its saleID. Is my query for creating a view wrong or it's how it should be?
Thanks.
A view is not a table. It does not hold any data: just a view to the actual tables. You can think of it as a stored query that you execute to get a result set whenever you query the view.
Keeping that in mind, what would happen when you execute the query the view is built with? since you are using left join, it probably means that you don't get any matching record on the sales table (or no record with the correct barcode on the salesItems table), therefor the salesId coloumn is null
The sales id is NULL because you have not inserted matching records into both sales tables (records for SaleItems and for Saless)
Once you insert sales data (matching records for SaleItems and for Saless) your join will have a value for Saless.SaleId as well.
Products | | SaleItems | | Saless
------------| join |------------------| join |---------
BarCode | | BarCode | SaleId | | SaleId
123 | | 123 | 456 | | 456
3545322 | | NULL | NULL | | NULL
Above you can see that you only get a result with all columns s.saleid, p.barcode, p.pname if the join can "match" records from table Products to SaleItems using the column BarCode and then match these records to Saless using the SaleId.
If there are no records in SaleItems (NULL) for the Barcode = 3545322 then the join can not match any records from Prodcuts to the other tables.
Is my query for creating a view wrong or it's how it should be?
That's how it should be. When you first insert a new row into Products there are no sales yet for that product, and so there is nothing to show for those fields. If you wanted to not see that product yet, you would define the view using an INNER JOIN instead of a LEFT JOIN.

Select from multiple tables with group by clause

I have these table in my database :
Ticket
-------------------------------
|ID int PK |
|Paid varchar(50) |
-------------------------------
TicketRow
----------------------------------
|ID int PK |
|TicketID_FK int |
|SHtimeID_FK int |
----------------------------------
I want to fetch the duplicated rows, that have same SHTiemID_FK and have Paid='ok' state in Ticket table, from TicketRow table.
I try this :
select SHtimeID_FK,count(*) as cnt from dbo.TicketRow
group by SHtimeID_FK
having count(*)>1
But i don't know how should i add Ticket table in my result set.
UPDATE :
I also need Ticket.ID in my resultset
If I understand your scenario correctly you can simply join these two tables by a inner join as I suppose TicketRow.TicketID_FK is a foreign key to Ticket table.
select SHtimeID_FK,count(*) as cnt
from dbo.TicketRow as tr inner join dbo.Ticket as t on tr.TicketID_FK=t.ID
where t.Paid='ok'
group by SHtimeID_FK
having count(*)>1

Which table exactly is the "left" table and "right" table in a JOIN statement (SQL)?

What makes a given table the left table?
Is it that the table is indicated in the "From" part of the query?
Or, is it the left table because it is on the left hand side of the = operator?
Are the following equivalent
SELECT *
FROM left_table
LEFT JOIN right_table ON left_table.right_id = right_table.id
and
SELECT *
FROM left_table
LEFT JOIN right_table on right_table.left_id = left_table.id
???
Thanks
The Left table is the first table in the select. Yes, your two examples are equivalent.
The right table is always the table that you are joining on. So yes, both of your statements are equivalent.
JOIN [Table] ON ...
[Table] is always the right table.
Roughly "left" is the result of everything that appears first in the whole FROM clause when reading from left to right - including the result of other JOINs, sub-queries, VIEWs and STORED PROCEDURES.
Both SQL statements are equivalent because the = operator at the ON part of the JOIN clause is symmetric (if a = b then b = a) so the result is the same no matter the order.
The regular join shows only the lines where the ON clause of the JOIN is true, while the LEFT JOIN shows also the records from "left" if the condition is false (showing NULL for any column from "right" present in the SELECT).
For example:
-- People: -- Car
id | name owner_id | model
---+------------ ---------+------------
1 | Paul 1 | Ferrari
2 | Nancy 2 | Porsche
3 | Arthur NULL | Lamborghini
4 | Alfred 10 | Maserati
> select people.name, car.model from people join car on car.owner_id=people.id;
name | model
---------+--------------
Paul | Ferrari
Nancy | Porsche
2 record(s) found
> select people.name, car.model from people left join car on
car.owner_id=people.id;
name | model
---------+--------------
Paul | Ferrari
Nancy | Porsche
Arthur | NULL
Alfred | NULL
4 record(s) found
> select people.name, car.model from people left join car on
people.id = car.owner_id;
name | model
---------+--------------
Paul | Ferrari
Nancy | Porsche
Arthur | NULL
Alfred | NULL
4 record(s) found
See this for a pretty good walkthrough on joins: http://en.wikipedia.org/wiki/Join_(SQL)
And yes, both statements are equivalent :-)
Yes, it's determined by the side of the JOIN operator the table appears on. Your two examples are indeed equivalent.
CREATE TABLE ORDERS (
ORDERID INT,
CUSTOMERID INT,
ORDERDATE DATE
);
INSERT INTO ORDERS VALUES (10123,10,DATE '16-08-20');
INSERT INTO ORDERS VALUES (10122,11,DATE '14-09-20');
INSERT INTO ORDERS VALUES (10121,12,DATE '10-10-20');
CREATE TABLE CUSTOMERS (
CUSTOMERID INT,
CUSTOMERNAME VARCHAR(20),
COUNTRY VARCHAR(20)
);
INSERT INTO CUSTOMERS VALUES (11 , 'BUDDHA','INDIA');
INSERT INTO CUSTOMERS VALUES (12 , 'JOHNWIK','UNITED STATES');
INSERT INTO CUSTOMERS VALUES (100, 'SERENA','UNITED KINGDOM');
discussing LEFT JOIN query:
select orders.orderid, customers.customername, orders.orderdate from orders
inner join customers on orders.customerid = customers.customerid;
If you want to know exact left and right tables. From left to right the table attached with from is [left] and table attached with join is [right].
Happy Hacking !!!