How to write the right SQL query statement using join condition? - sql

There are three fields in a table, all of them refer the same field in another table, like this:
table1
-------
! a_term_id* ! b_term_id* ! c_term_id* !
! ! ! !
table2
-------
! term_id ! term_title ! term_description !
! ------- ! ! !
columns a_term_id, b_term_id, c_term_id all refer to term_id
How should I write the SQL statement to retrieve the three fields' info?

I think you need to know how Sql_Join works. Here on W3Schools you can find useful examples.
A simple example:
SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.P_Id=Orders.P_Id
ORDER BY Persons.LastName
EDIT
You can try something like this:
SELECT * FROM tableA
inner join tableB on tableA.term_id = tableB.term_id
inner join tableC on tableA.term_id = tableC.term_id;
It an example you can modify as per your need.
Edit 2
SELECT * FROM tableB
JOIN tableA AS tableA1 ON tableB.term_id = tableA1.a_term_id
JOIN tableA AS tableA2 ON tableB.term_id = tableA2.b_term_id
JOIN tableA AS tableA3 ON tableB.term_id = tableA3.c_term_id

Here is an example. Suppose that we have two tables - Employees and Companies:
CREATE TABLE Employees(
Id int,
Name varchar(128),
CompanyId int);
CREATE TABLE Companies(
Id int,
Name varchar(128),
Address varchar(1024),
DateFounded datetime);
The following SQL query will join the tables:
SELECT * FROM Employees
INNER JOIN Companies
ON Employees.CompanyId = Companies.Id

Your question is a bit unclear, but I'll guess that you have a table A with three fields, each of which identifies a (possibly different) row from table B. You want to retrieve info from each of those rows of table B based on the field values of a single row of table A.
To do this, you will need to join table A to table B three times, once for each field of table A. Each join should be given an alias and then you can refer to the fields in the joined table by qualified field names.
SELECT b1.info, b2.info, b3.info
FROM A JOIN B AS b1 ON field1 = b1.field
JOIN B AS b2 ON field2 = b2.field
JOIN B AS b3 ON field3 = b2.field
WHERE ...

SELECT
t.a_term_id, a.term_title, a.term_description,
t.b_term_id, b.term_title, b.term_description,
t.c_term_id, c.term_title, c.term_description
FROM abc_terms t JOIN ( terms_info a, terms_info b, terms_info c )
ON ( t.a_term_id = a.term_id
AND t.b_term_id = b.term_id
AND t.c_term_id = c.term_id )

Related

Create a additional row from join sql?

I have 2 tables: Person and House with 1-n relation.
I want to the result return as picture below:
Row always have a Person column with a null House column.
Thanks.
you can use unionall to join the result set with person table something like
select p.name,h.name as housename from person p join house h on p.id=h.personid
union all (select name,null from person)
order by name,housename

SQL query - Return 0 for the column if no record found

I will like to see the specific fields returns with 0 value when there is no record found.
Below are my SQL queries that I have tried so far.
SELECT Customer, Address, Number of lines, Date
FROM table_name
WHERE Date = '30-5-2022' AND Customer IN (A, B, C)
What it returns is only 1 row as below.
Customer
Address
Number of Lines
Date
A
3
RF
30-5-2022
But what I expected to see is:
Customer
Address
Number of Lines
Date
A
UK
33
30-5-2022
B
0
0
30-5-2022
C
0
0
30-5-2022
The customer B and C has no record on 30-5-2022 but I will still need to see the rows but certain columns can be 0.
Please advise if anything that I have missed out? Thanks a lot!
Try below query:
SELECT A.Customer, ISNULL(B.Address, 0),
ISNULL(B.[Number of lines],0), ISNULL(B.Date, '30-05-2022') Date
FROM
(
SELECT DISTINCT Customer
FROM table_name
) A
LEFT JOIN table_name B
ON A.Customer = B.Customer
AND B.Date = '30-5-2022'
This will output all the customers present in the table. You can filter the customers with WHERE clause in the end of the above query based on your requirement.
dbfiddle Link
Assuming customers are in one table (cust) and other stuff in another table (table_name) and they are connected with an id called custid, you need some sweet, sweet left join action, such as:
SELECT c.Customer, c.Address, isnull([Number of lines],0), d.Date
FROM cust c left join table_name d on c.custid = d.custid and
d.Date = '30-5-2022' where
c.Customer IN ('A', 'B', 'C')
You need to put A, B, C in a table and left-join the main table to it. All other conditions must then go in the ON clause not the WHERE.
You can use a virtual VALUES clause for this
SELECT Customer, Address, Number of lines, Date
FROM (VALUES
('A'),
('B'),
('C')
) v(Customer)
LEFT JOIN table_name tn ON tn.Customer = v.Customer
AND tn.Date = '30-5-2022';
Alternatively you can pass in a Table Valued Parameter, or use a table variable. Don't forget to add a primary key.
DECLARE #tmp TABLE (Customer varchar(100) PRIMARY KEY);
INSERT #tmp(Customer) VALUES
('A'),
('B'),
('C');
SELECT Customer, Address, Number of lines, Date
FROM #tmp v
LEFT JOIN table_name tn ON tn.Customer = v.Customer
AND tn.Date = '30-5-2022';

SQL JOIN to get the compare two values/row from table "A" and the same row from table "B"

I have two tables with the following rows
Table A (transaction)
Order Seller Customer
1 300 500
Table B (Persons)
PersonID FullName
300 Peter White
500 Scott Bold
I want a result like this
Order Seller Customer FullName (Seller) FullName (customer)
1 300 500 Peter White Scott Bold
I've tried multiple things however which makes more sense is a join a table twice, however I'm getting:
Ambiguous column name
This is SQL Server 2019.
Basically I'm looking to retrieve info from the same table instead of creating additional tables. Is that possible? If yes, how do you do? Thank you in advance.
As #jarlh wrote in comment:
select t.order, t.seller, t.customer, sel.fullname, cust.fullname
from transaction t
join persons sel -- sel is an alias to persons table
on sel.personid = t.seller
join persons cust
on cust.personid = t.customer;
Query with join will return the result as long as both seller and customer exist in persons table -- here it should as source table names transactions :).
I have another form of query it still join table B twice.
This is archaic syntax which I don't recommend but for beginner know the concept of JOIN:
select t.*,B.FullName as FullName (customer) from
(
select A.Order,A.Seller,A.Customer,B.FullName as FullName(Seller)
from A,B where A.Seller=B.PersionID
) t, B where t.Customer=B.PersionID
The proper way of JOIN:
select t.*,B.FullName as FullName (customer) from
(
select A.Order,A.Seller,A.Customer,B.FullName as FullName(Seller)
from A JOIN B ON A.Seller=B.PersionID
) t JOIN B ON t.Customer=B.PersionID
Hoping this can help you.

Complex update with three tables involved

I am using Postgresql in my company as a primary store and I'm struggling to implement an update query involving three different tables.
Here is the schema :
Table 1 has entity_id, entity_type and company_id (referencing Company.id) columns.
Company has id column
Special_company has id (which corresponds to Table1.entity_id) and company_id (referencing Company.id)
I would like to update all the rows of Table 1 where Table1.entity_type = 'SpecialCompany' in order to fill Table1.company_id such that :
Table1.entity_id = SpecialCompany.id and SpecialCompany.company_id = Company.id
I've started something like that:
UPDATE Table1
SET company_id = (select c.id
FROM company c
INNER JOIN special_company w ON c.id=w.company_id
WHERE w.id=709)
WHERE entity_type='SpecialCompany' AND entity_id=709;
But I am not able to replace 709 by all the Table1.entity_id where Table1.entity_type = 'SpecialCompany'.
Any help would be much appreciated.
I assume you are looking for something like this.
update t
set t.company_id=c.id
from
Company C
INNER JOIN special_company w ON c.id=w.company_id
INNER JOIN Table1 t on t.entity_id=w.entity_id
Where t.entity_type = 'SpecialCompany'
I'm answering to my question as I found the solution :
UPDATE Table1 t
SET company_id = c.id
FROM Company c
INNER JOIN special_company w ON c.id=w.company_id
WHERE
t.entity_type = 'SpecialCompany' AND t.entity_id=w.id;
Thanks #Krishna for your help !

How do I do an SQL query based on a foreign key field?

I have the following tables:
people:
id, name
parent:
id, people_id, name
I have tried the following:
SELECT * FROM people
LEFT JOIN parent ON people.id = parent.people_id
WHERE parent.name != 'Carol';
How do I find all the people whose parent's name is not Carol?
You can try below code
select people.name from people
inner join parent on people.id=parent.people_id
where parent.name not in ('Carol')
If the two tables are to be queried by using Foreign Key.
If you want to get all records from one table that have some related entry in a second table then use Inner join
Select * from People INNER JOIN parent ON people.id = parent.people_id
WHERE parent.name <> 'Carol'
Similarly LEFT JOIN will get all records from the LEFT linked table but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL
First of all, why would you need two tables? why can't you have a single table named "Person" with ID,Name,ParentID columns
Where ParentID will be optional and reference the ID if it has got parent.
And run the following query
select * from PERSON where Name not like 'Carol%' and ParentID IS NOT NULL;
SELECT * FROM people WHERE EXISTS(SELECT 1 FROM parent WHERE people_id = id AND name <> 'Carol')
First of all the table structure you have taken restrict the future growth. Like in future if you want to add parents of your parents then it wont work in this table structure.
You can do like :
id | parent_id | people_name
Here you can make parent_id null for the parent and add parent_id as id for those who have parent. Here to retrieve you have to use SELF join(join in the same table)
`
Select * from people P
INNER JOIN parent PA ON PA.people_id = P._id
where PA.name not in ('Carol')
`
Difference between INNER JOIN and LEFT OUTER JOIN
is
1) INNER JOIN bring only similar data between two table
for ex if in people table parent_id table is nullable then it will not discard the complete row,but in case of LEFT OUTER JOIN it will bring all the rows from LEFT table as well as related table from right table.with all null in right joined row..