how to do a left join with no duplicate columns? - sql

I have to join 2 tables and the first table I'm joining consists of:
Physicians (ID, FirstName, LastName, PracticeID, SpecialtyID, Email)
and the second table I have is:
PhysicianSpecialties( SpecialtyID, SpecialtyName)
I wrote this query to join the tables together
Select *
from physicians
right join PhysicianSpecialities
on PhysicianSpecialities.SpecialtyID = Physicians.SpecialtyID
and when I left Join them the table is now
(ID, FirstName, LastName, PracticeID, SpecialtyID, Email, SpecialtyID, SpecialtyName)
how can I rewrite this so there is only one "SpecialtyID" Column?

You didn't specify the DBMS product you are using, but: in standard SQL you can join with the USING operator if the join columns have the same name in both tables.
In this case, the "duplicated" column will automatically be removed from the result.
Select *
from physicians
right join PhysicianSpecialities using (SpecialtyID)
Not all DBMS products support that though.

You need to specify the column names of both tables instead of (*)
Select a.*,b.SpecialtyName
from physicians a
right join PhysicianSpecialities b
on b.SpecialtyID = a.SpecialtyID

Use
SELECT
physicians.ID, physicians.FirstName, physicians.LastName,
physicians.PracticeID, physicians.SpecialtyID, physicians.Email,
PhysicianSpecialities.SpecialtyName
instead of SELECT *, hence your query goes like:
SELECT
physicians.ID, physicians.FirstName, physicians.LastName,
physicians.PracticeID, physicians.SpecialtyID, physicians.Email,
PhysicianSpecialities.SpecialtyName
FROM
physicians
LEFT JOIN
PhysicianSpecialities ON Physicians.SpecialtyID = PhysicianSpecialities.SpecialtyID;
I hope it will return the desired result.

Related

How do I check for occurrence in two tables simultaneously

I have a SQL query (oracle) that checks for both persons and firms, the problem is that you won't find a company in the user table and the other way around.
As of now I write this in two queries, but I would like to make this into one query (for example if I can get some help creating a temporay table)
I have a info table that tells me if this is a user, a company or both
The sql looks a bit like this:
Table1:
fk_id,
info1,
info2,
info3
Info_table:
fk_id,
<info if user, company or both>
User_table:
firstname,
lastname,
adress,
fk_id
Company_table:
Companyname,
adress,
fk_id
I would like to eighter 1:
Make a temporary table that looks like this:
Temptable:
fk_id,
firstname(if user or both, else empty),
lastname(if user, else companyname),
adress
or make a query like this:
select table1.info1, table1.info2, firstname, lastname, adress
from table1,
user_table,
company_table,
info_table
where table1.fk_id = user_table.fk_id (if user or both)
or table1.fk_id = company_table.fk_id (if company)
Any tips on how to solve this would be great. What is the best solution (making a temp table or to add this into the initial query)?
Use left outer join (in this response i'll use the + operator for convenience)
select table1.info1, table1.info2,
firstname,
nvl(lastname,company_name) lastname,
nvl(user_table.adress,company_table.adress) adress
from table1,
user_table,
company_table,
info_table
where
table1.fk_id=info_table.fk_id(+)
and table1.fk_id = user_table.fk_id(+) --(if user or both)
and table1.fk_id = company_table.fk_id(+) --(if company)
You can use a union:
quick example:
select firstname
,lastname as name
,'person_table' as source_table
from person_table
union
select null
,company_name
,'company_table'
from company_table;
The result will be a list of both persons and companies.
The correct way to write this query:
select t1.info1, t1.info2, ut.firstname,
coalesce(ut.lastname, ct.company_name) as lastname,
coalesce(ut.adress, ct.adress) as address
from table1 t1 left join
info_table it
on t1.fk_id = it.fk_id left join
user_table ut
on t1.fk_id = ut.fk_id and
it.info in ('both', 'user') left join
company_table ct
on t1.fk_id = ct.fk_id and
ct.info in ('both', 'company') ;
Notes:
This uses proper, explicit, standard JOIN syntax, as recommended by Oracle itself.
This only does the joins when the type specifies that the join is appropriate.
This uses COALESCE(), a standard function, rather than the bespoke NVL().
All column names are qualified.
This uses table aliases, so the query is easier to write and to read.

SQL join beween tables with if statement

Say, I have the following two tables:
Table customer:
id, salutation, forename, lastname, companyID
and a table company:
Company_id, Company_name, Company_address
and I want to have an evaluation over all users and their company (if they belong to one)
salutation, forename, lastname, companyName
that would amount basically to a very easy script:
select salutation, forename, lastname, company_name
from customer, company
where companyID=Company_id;
The trouble now is just, that companyID can be null. (A customer doesn't need to be part of a company). And since there is no companyID null entry in the company table and any customer who has no company ID listed is omitted due to the joint statement.
Of couse I could divide it into two scripts one for companyid=null and one for not null and mix them with a UNION command, but is there perhaps something like an if statement?
something like:
select salutation, forename, lastname, placeholder
from customer, company
where
if companyID=null then placeholder=null
else (companyID=Company_id and placeholder=company_name);
?
I know there is a case statement, that can check on the field's value and return something else instead, but is there a way to combine that with a joint to another table?
You are looking for an outer join:
select cu.salutation, cu.forename, cu.lastname, co.company_name
from customer cu
left join company co on cu.companyID = co.Company_id;
In general you should stop using the ancient implicit join syntax in the where clause and use an explicit JOIN operator. That is also the only cross-DBMS way to actually do an outer join (all DBMS that supported some proprietary outer join syntax have deprecated that)
Try this
select salutation, forename, lastname, placeholder
from customer, company
where
(companyID=null and placeholder=null )
OR
(companyID=Company_id and placeholder=company_name);
Use a left join instead of an inner join
select a.salutation, a.forename, a.lastname, a.company_name
from customer a
left outer join company b
on a.companyID=b.companyID;

How to display data from two tables in a SQL Server database in a gridview?

I want show data in a gridview from two tables that have a relationship but it show only some column in table 1. I using an INNER JOIN query.
dept (IDD, deptname)
person (ID, name, birthday, address, IDD)
I want to display the columns ID, name, deptname in a gridview, but deptname is not showing any value.
Thanks!
The select query is straightforward:
select
person.ID,
person.name,
department.deptname
from person
inner join department on person.IDD = department.IDD
If you aren't getting any results, then perhaps no records meet your join criteria. You can change the inner join to a full outer join and examine the results to check if this is the case.

How To Code a Multi-Join SQL Query And Get Query Results Even When 1 Table Lacks A Joining Row

I have the following query statement:
$query_string = '
SELECT customerID, lastName, firstName, companyName, email, citizenship, primaryLanguage
FROM customers
JOIN citizenships USING(citizenshipID)
JOIN languages USING(languageID)
JOIN paymentMethods USING(customerID)
WHERE customerID = "1"
';
Currently the customers, citizens and languages tables each contain rows and join properly. My query result returns 1 row for customer #1.
The paymentMethods table does not contain any rows at this time. When I add the join syntax for paymentMethods to the query string, my query result returns 0 rows for customer #1.
I want to join on paymentMethods and only return a row from the paymentMethods table when one exists without causing no customer rows to be returned otherwise.
How might I tweak my JOIN syntax to make that happen?
Thank you.
Replace it with LEFT JOIN:
SELECT customerID, lastName, firstName, companyName, email, citizenship, primaryLanguage
FROM customers
JOIN citizenships
USING (citizenshipID)
JOIN languages
USING (languageID)
LEFT JOIN
paymentMethods
USING (customerID)
WHERE customerID = "1"
$query_string = '
SELECT customerID, lastName, firstName, companyName, email, citizenship, primaryLanguage
FROM customers
JOIN citizenships USING(citizenshipID)
JOIN languages USING(primaryLanguageID)
LEFT JOIN paymentMethids USING(customerID)
WHERE customerID = "1"
';

sql server - how to modify values in a query statement?

I have a statement like this:
select lastname,firstname,email,floorid
from employee
where locationid=1
and (statusid=1 or statusid=3)
order by floorid,lastname,firstname,email
The problem is the column floorid. The result of this query is showing the id of the floors.
There is this table called floor (has like 30 rows), which has columns id and floornumber. The floorid (in above statement) values match the id of the table floor.
I want the above query to switch the floorid values into the associated values of the floornumber column in the floor table.
Can anyone show me how to do this please?
I am using Microsoft sql server 2008 r2.
I am new to sql and I need a clear and understandable method if possible.
select lastname,
firstname,
email,
floor.floornumber
from employee
inner join floor on floor.id = employee.floorid
where locationid = 1
and (statusid = 1 or statusid = 3)
order by floorid, lastname, firstname, email
You have to do a simple join where you check, if the floorid matches the id of your floor table. Then you use the floornumber of the table floor.
select a.lastname,a.firstname,a.email,b.floornumber
from employee a
join floor b on a.floorid = b.id
where a.locationid=1 and (a.statusid=1 or a.statusid=3)
order by a.floorid,a.lastname,a.firstname,a.email
You need to use a join.
This will join the two tables on a certain field.
This way you can SELECTcolumns from more than one table at the time.
When you join two tables you have to specify on which column you want to join them.
In your example, you'd have to do this:
from employee join floor on employee.floorid = floor.id
Since you are new to SQL you must know a few things. With the other enaswers you have on this question, people use aliases instead of repeating the table name.
from employee a join floor b
means that from now on the table employee will be known as a and the table floor as b. This is really usefull when you have a lot of joins to do.
Now let's say both table have a column name. In your select you have to say from which table you want to pick the column name. If you only write this
SELECT name from Employee a join floor b on a.id = b.id
the compiler won't understand from which table you want to get the column name. You would have to specify it like this :
SELECT Employee.name from Employee a join floor b on a.id = b.id or if you prefer with aliases :
SELECT a.name from Employee a join floor b on a.id = b.id
Finally there are many type of joins.
Inner join ( what you are using because simply typing Join will refer to an inner join.
Left outer join
Right outer join
Self join
...
To should refer to this article about joins to know how to use them correctly.
Hope this helps.