Having trouble joining tables - sql

I'm trying to write a query to display the name of each passenger with their fare.
Here's what I have so far -- it gives no errors, but also no results:
-- Write a query to display the Name of each passenger as well as the fare for their trip.
select passenger.name, departure_info.fare * passenger.quantity AS passenger_fare
from passenger, seat_passenger, manages, departure_info, seat_info
where departure_info.Dept_id=manages.Dept_id
AND manages.Seat_id=seat_info.Seat_id
AND seat_info.Seat_id=seat_passenger.Seat_id
AND seat_passenger.Pass_id=passenger.pass_id
Here is the relationship view of the tables http://i.imgur.com/R4EFthY.png

using proper joins syntax will make this query from your query
select
p.name, di.fare * p.quantity as passenger_fare
from passenger as p
inner join seat_passenger as sp on sp.pass_id = p.pass_id
inner join seat_info as si on si.seat_id = sp.seat_id
inner join manages as m on m.seat_id = si.seat_id
inner join departure_info as di on di.dept_it = m.dept_id
I suggest you to turn inner joins into left outer joins and see what you're missing
select
p.name, di.fare * p.quantity as passenger_fare,
sp.pass_id, si.seat_id, m.seat_id, di.dept_id
from passenger as p
left outer join seat_passenger as sp on sp.pass_id = p.pass_id
left outer join seat_info as si on si.seat_id = sp.seat_id
left outer join manages as m on m.seat_id = si.seat_id
left outer join departure_info as di on di.dept_it = m.dept_id
Actually, you could even remove unused joins (if you don't miss some records from seat_info):
select
p.name, di.fare * p.quantity as passenger_fare
from passenger as p
inner join seat_passenger as sp on sp.pass_id = p.pass_id
inner join manages as m on m.seat_id = sp.seat_id
inner join departure_info as di on di.dept_it = m.dept_id

Related

Unnecessary LEFT JOINs on all Child tables from main LEFT JOIN table required in query for correct result

I am LEFT JOIN-ing the table RECALLS_T with EVENTS_T. Some Recalls do not have any Events, and for those I want a blank row returned.
However, once an entry in EVENTS_T exists, all the following extra tables from EVENTS_T which I also need (ANSWERS_T, ACTIVITY_QUESTIONS_T, ACTIVITES_T) are guaranteed to have entries. For these subsequent tables there is no need to do a LEFT JOIN from their parent, it can be an INNER JOIN just as well.
But if I do the following, the query does not return blank EVENTS_T rows for a RECALLS_T.
SELECT ..
FROM
recalls_t r
LEFT JOIN events_t e ON ( r.id = e.recall_id ) --Only LEFT JOIN this main table
INNER JOIN answers_t ans ON (ans.event_id = e.id)
INNER JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
INNER JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)
Instead, I need to change every subsequent INNER JOIN to a LEFT JOIN as well, in order to get Recalls with blank Events.
SELECT ..
FROM
recalls_t r
LEFT JOIN events_t e ON ( r.id = e.recall_id )
LEFT JOIN answers_t ans ON (ans.event_id = e.id)
LEFT JOIN activity_questions_t aq ON (ans.activity_question_id = aq.id)
LEFT JOIN PUBLIC.activities_t act ON (aq.activity_id = act.id)
I'm just not clear on why I have to do this. The top-level optional join is all I care about, but the downstream joins from EVENTS_T are guaranteed to have data provided the Event exists. Shouldn't the top-level single EVENTS_T join be enough? I'm using Postgres.
The reason you need to do this is because rows preserved by the outer join will have NULL for all columns from events - so inner joining using an equality condition on e.id will remove them from the result again.
you can move the ON clause to the end of the query to give your desired semantics.
The left join is then on the virtual result of inner joining events_t, answers_t, activity_questions_t and activities_t
SELECT ...
FROM recalls_t r
LEFT JOIN events_t e
INNER JOIN answers_t ans
ON ( ans.event_id = e.id )
INNER JOIN activity_questions_t aq
ON ( ans.activity_question_id = aq.id )
INNER JOIN PUBLIC.activities_t act
ON ( aq.activity_id = act.id )
ON ( r.id = e.recall_id )
Or you could consider a RIGHT JOIN here instead
SELECT ...
FROM events_t e
INNER JOIN answers_t ans
ON ( ans.event_id = e.id )
INNER JOIN activity_questions_t aq
ON ( ans.activity_question_id = aq.id )
INNER JOIN PUBLIC.activities_t act
ON ( aq.activity_id = act.id )
RIGHT JOIN recalls_t r
ON ( r.id = e.recall_id )
You have to do this because answers_t`` is joining onevents_s. If thejoinkey (e.recall_id) isNULL`, then there will be no match. And the inner join will not return the row. And so on for the other tables.
You seem to understand the fix. Once you use left join, you need to continue using left join for those tables that are connected to the second table of the left join.

Convert fractions into decimal in sql using a function and select statements

Every time I try to run the following in Microsoft SQL Server Management Studio, I get an error message
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations
Is there anyway at all to run this in one statement?
The reason why I'm calling a function in this statement (dbo.ufn_ConvertJambDepthFractionToNumber) is because the dbo.CDS_Shipments_Door_Overall_Jamb_Depth.InstructionValue AS [Jamb Depth] column spits out values like 4 1/6", 3 1/4", 6 9/16". I'm using that function to try to convert the varchar values (4 1/6", 3 1/4", 6 9/16") into decimals.
If there is a better way to do that, I'm all ears.
use BeechworthProdWTS
declare #jamb_depth as varchar
SELECT DISTINCT
dbo.QuoteShippingAddress.Name AS [CDS Location],
dbo.QuoteShippingAddress.Address1 AS [Quote Shipping Address1],
dbo.CDS_Shipments_Door_Overall_Jamb_Depth.InstructionValue AS [Jamb Depth],
dbo.CDS_Shipments_Door_Count_view.Doors,
dbo.CDS_Shipments_Screen_Count_view.Screens,
dbo.CDS_Shipments_Windows_Count_view.Windows,
dbo.LineItemMaster.LineNumber,
#jamb_depth = dbo.CDS_Shipments_Door_Overall_Jamb_Depth.InstructionValue,
dbo.ufn_ConvertJambDepthFractionToNumber(#jamb_depth)
FROM
dbo.Quotes
INNER JOIN
dbo.QuoteShippingAddress WITH (NOLOCK) ON dbo.Quotes.QuoteID = dbo.QuoteShippingAddress.QuoteID
INNER JOIN
dbo.Clients WITH (NOLOCK) ON dbo.Quotes.ClientID = dbo.Clients.ClientID
INNER JOIN
dbo.CustomerProjectInformation WITH (NOLOCK) ON dbo.Quotes.QuoteID = dbo.CustomerProjectInformation.QuoteID
INNER JOIN
dbo.LineItemMaster WITH (NOLOCK) ON dbo.Quotes.QuoteID = dbo.LineItemMaster.QuoteID
INNER JOIN
dbo.LineItems WITH (NOLOCK) ON dbo.LineItemMaster.LineItemMasterID = dbo.LineItems.LineItemMasterID
INNER JOIN
dbo.WorkOrders WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.WorkOrders.LineItemID
LEFT OUTER JOIN
dbo.CDS_Shipments_Door_Count_view WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.CDS_Shipments_Door_Count_view.LineItemID
LEFT OUTER JOIN
dbo.CDS_Shipments_Door_Overall_Jamb_Depth WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.CDS_Shipments_Door_Overall_Jamb_Depth.LineItemID
LEFT OUTER JOIN
dbo.CDS_Shipments_Screen_Count_view WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.CDS_Shipments_Screen_Count_view.LineItemID
LEFT OUTER JOIN
dbo.CDS_Shipments_Windows_Count_view WITH (NOLOCK) ON dbo.LineItems.LineItemID = dbo.CDS_Shipments_Windows_Count_view.LineItemID
Since you say you are pretty new to SQL I reformatted this using aliases so you can see how much difference it make visually. This doesn't affect performance but it does keep the developer sane. Also, not really sure what you are trying to do with your scalar but maybe trying to get the value for each row?
Cleaned up your query might look something like this.
SELECT DISTINCT
qsa.Name AS [CDS Location],
qsa.Address1 AS [Quote Shipping Address1],
sdojd.InstructionValue AS [Jamb Depth],
sdcv.Doors,
sscv.Screens,
swcv.Windows,
lim.LineNumber,
--#jamb_depth = sdojd.InstructionValue, --not really sure what you are trying to do here
--dbo.ufn_ConvertJambDepthFractionToNumber(#jamb_depth)
JambDepth = dbo.ufn_ConvertJambDepthFractionToNumber(sdojd.InstructionValue)
FROM dbo.Quotes q
INNER JOIN dbo.QuoteShippingAddress qsa ON q.QuoteID = qsa.QuoteID
INNER JOIN dbo.Clients c ON q.ClientID = c.ClientID
INNER JOIN dbo.CustomerProjectInformation cpi ON q.QuoteID = cpi.QuoteID
INNER JOIN dbo.LineItemMaster lim ON q.QuoteID = lim.QuoteID
INNER JOIN dbo.LineItems li ON lim.LineItemMasterID = li.LineItemMasterID
INNER JOIN dbo.WorkOrders wo ON li.LineItemID = wo.LineItemID
LEFT OUTER JOIN dbo.CDS_Shipments_Door_Count_view sdcv ON li.LineItemID = sdcv.LineItemID
LEFT OUTER JOIN dbo.CDS_Shipments_Door_Overall_Jamb_Depth sdojd ON li.LineItemID = sdojd.LineItemID
LEFT OUTER JOIN dbo.CDS_Shipments_Screen_Count_view sscv ON li.LineItemID = sscv.LineItemID
LEFT OUTER JOIN dbo.CDS_Shipments_Windows_Count_view swcv ON li.LineItemID = swcv.LineItemID

LEFT JOINS in MS Access

I am trying to troubleshoot someone else's MS Access query and keep getting an invalid operation error. The Help doesn't seem to apply as I am just running a query. It all works as INNER JOINS but when I switch back to the LEFT JOIN the error.
SELECT *
FROM ((((orders
INNER JOIN orders_customers ON orders.CUST_ORDER_ID = orders_customers.ID)
LEFT JOIN quoted_theory ON orders.PART_ID = quoted_theory.PART_ID)
LEFT JOIN conversions ON orders.PART_ID = conversions.PART_ID)
LEFT JOIN dbo_WO_Header ON orders.CUST_ORDER_ID = dbo_WO_Header.PPC_Number)
INNER JOIN lines_qry ON orders.CUST_ORDER_ID = lines_qry.WORKORDER_BASE_ID
I can get one level of LEFT JOIN, but each time I add a second LEFT JOIN the error pops up.
Access' db engine frequently balks when mixing INNER and LEFT joins. If that query works without the last inner join ...
SELECT *
FROM
(((orders INNER JOIN orders_customers
ON orders.CUST_ORDER_ID = orders_customers.ID)
LEFT JOIN quoted_theory
ON orders.PART_ID = quoted_theory.PART_ID)
LEFT JOIN conversions
ON orders.PART_ID = conversions.PART_ID)
LEFT JOIN dbo_WO_Header
ON orders.CUST_ORDER_ID = dbo_WO_Header.PPC_Number
... then you could try that part as a subquery and inner join lines_qry to the subquery. It might get past the error.
SELECT *
FROM
(
SELECT *
FROM
(((orders INNER JOIN orders_customers
ON orders.CUST_ORDER_ID = orders_customers.ID)
LEFT JOIN quoted_theory
ON orders.PART_ID = quoted_theory.PART_ID)
LEFT JOIN conversions
ON orders.PART_ID = conversions.PART_ID)
LEFT JOIN dbo_WO_Header
ON orders.CUST_ORDER_ID = dbo_WO_Header.PPC_Number
) AS sub
INNER JOIN lines_qry
ON sub.CUST_ORDER_ID = lines_qry.WORKORDER_BASE_ID
If any other table besides orders includes a field named CUST_ORDER_ID, you will need something other than SELECT * within the subquery to avoid ambiguity.
SELECT *
FROM
(
SELECT *
FROM
(((orders INNER JOIN orders_customers
ON orders.CUST_ORDER_ID = orders_customers.ID)
LEFT JOIN quoted_theory
ON orders.PART_ID = quoted_theory.PART_ID)
LEFT JOIN conversions
ON orders.PART_ID = conversions.PART_ID)
LEFT JOIN dbo_WO_Header
ON orders.CUST_ORDER_ID = dbo_WO_Header.PPC_Number
) AS sub
INNER JOIN lines_qry
ON sub.CUST_ORDER_ID = lines_qry.WORKORDER_BASE_ID

Can you have an INNER JOIN without the ON keyword?

While debugging into some Oracle code, I came across this query:
SELECT TPM_TASK.TASKID FROM TPM_GROUP
INNER JOIN TPM_USERGROUPS ON TPM_GROUP.GROUPID = TPM_USERGROUPS.GROUPID
INNER JOIN TPM_TASK
INNER JOIN TPM_GROUPTASKS ON TPM_TASK.TASKID = TPM_GROUPTASKS.TASKID
INNER JOIN TPM_PROJECTVERSION ON TPM_TASK.PROJECTID = TPM_PROJECTVERSION.PROJECTID AND TPM_TASK.VERSIONID = TPM_PROJECTVERSION.VERSIONID
INNER JOIN TPM_TASKSTAGE ON TPM_TASK.STAGEID = TPM_TASKSTAGE.STAGEID
INNER JOIN TPM_PROJECTSTAGE ON TPM_PROJECTVERSION.STAGEID = TPM_PROJECTSTAGE.STAGEID
ON TPM_GROUP.GROUPID = TPM_GROUPTASKS.GROUPID
I'm confused by the line:
INNER JOIN TPM_TASK
I haven't seen a JOIN without an ON clause before. Also confusing is the line:
ON TPM_GROUP.GROUPID = TPM_GROUPTASKS.GROUPID
This seems like a random ON clause without any matching JOIN. The query runs without any errors, and returns a bunch of data, so obvious the syntax is perfectly valid. Can someone shed some light on exactly what's going on here?
Small universe... I ran across a tool generating this syntax yesterday and was rather flummoxed.
Apparently,
FROM a
INNER JOIN b
INNER JOIN c ON (b.id = c.id)
ON (a.id = c.id)
is equivalent to a nested subquery
FROM a
INNER JOIN (SELECT <<list of columns>>
FROM b
INNER JOIN c ON (b.id=c.id)) c
ON (a.id = c.id)
I think that this is only a problem of ordering your query (since there are only INNER JOINs, the order of them is not really that important). I rearrenged your query and now it looks like this:
SELECT TPM_TASK.TASKID
FROM TPM_GROUP
INNER JOIN TPM_USERGROUPS
ON TPM_GROUP.GROUPID = TPM_USERGROUPS.GROUPID
INNER JOIN TPM_GROUPTASKS
ON TPM_GROUP.GROUPID = TPM_GROUPTASKS.GROUPID
INNER JOIN TPM_TASK
ON TPM_TASK.TASKID = TPM_GROUPTASKS.TASKID
INNER JOIN TPM_PROJECTVERSION
ON TPM_TASK.PROJECTID = TPM_PROJECTVERSION.PROJECTID
AND TPM_TASK.VERSIONID = TPM_PROJECTVERSION.VERSIONID
INNER JOIN TPM_TASKSTAGE
ON TPM_TASK.STAGEID = TPM_TASKSTAGE.STAGEID
INNER JOIN TPM_PROJECTSTAGE
ON TPM_PROJECTVERSION.STAGEID = TPM_PROJECTSTAGE.STAGEID
Does it make more sense to you now?, it does to me.
It'd look fine if it had parenthesis in there...
SELECT TPM_TASK.TASKID
FROM
TPM_GROUP
INNER JOIN TPM_USERGROUPS ON TPM_GROUP.GROUPID = TPM_USERGROUPS.GROUPID
INNER JOIN (
TPM_TASK
INNER JOIN TPM_GROUPTASKS ON TPM_TASK.TASKID = TPM_GROUPTASKS.TASKID
INNER JOIN TPM_PROJECTVERSION ON TPM_TASK.PROJECTID = TPM_PROJECTVERSION.PROJECTID
AND TPM_TASK.VERSIONID = TPM_PROJECTVERSION.VERSIONID
INNER JOIN TPM_TASKSTAGE ON TPM_TASK.STAGEID = TPM_TASKSTAGE.STAGEID
INNER JOIN TPM_PROJECTSTAGE ON TPM_PROJECTVERSION.STAGEID = TPM_PROJECTSTAGE.STAGEID
) ON TPM_GROUP.GROUPID = TPM_GROUPTASKS.GROUPID
but since they are all inner joins I agree with Lamak's answer.

Sql problem with my query

SELECT
dbo.pi_employee.emp_firstname, dbo.pi_employee.emp_lastname,
dbo.pi_employee.emp_no, dbo.pi_employee.emp_cnic,
dbo.pi_employee.emp_currentadd, dbo.pi_employee.emp_cellph,
dbo.pi_employee.emp_birthday, pi_jobtitle_1.jobtitle_name,
dbo.pi_employee.emp_joindate, dbo.pi_education.edu_degree,
dbo.pi_education.edu_year, dbo.pi_employee.emp_pension,
dbo.pi_employee.emp_age, dbo.pi_employee.emp_service,
dbo.pi_employee.emp_terminate, dbo.pi_employee.emp_termdate,
dbo.pi_employee.emp_basicofpay, dbo.pi_employee.emp_terminationreason,
dbo.pi_employee.emp_terminationdate, dbo.pi_employee.emp_status,
dbo.pi_employee.emp_gender, dbo.pi_employee.emp_maritalstatus,
dbo.pi_employee.emp_paymethod, dbo.pi_employee.emp_leaveentitle,
dbo.pi_employee.emp_confirmation, dbo.pi_employee.emp_title,
dbo.pi_employee.emp_basicamount, dbo.pi_salgrade.salgrade_name,
dbo.tbl_emp_status.StatusName, dbo.pi_skills.skill_type,
dbo.pi_location.loc_name, pi_location_1.loc_name AS wcity,
dbo.pi_jobtitlehist.jthSaleGradetype, dbo.pi_workexp.exp_serperiod,
dbo.pi_employee.emp_domicile, dbo.pi_skills.skill_type AS Skill,
dbo.pi_skills.skill_exp, dbo.pi_education.edu_degree AS Degree,
dbo.pi_education.edu_uni, dbo.pi_education.edu_distinction,
dbo.pi_lochistory.lhstart_date, dbo.pi_lochistory.lhend_date
FROM
dbo.pi_location
RIGHT OUTER JOIN
dbo.pi_workexp
RIGHT OUTER JOIN
dbo.pi_employee ON dbo.pi_workexp.emp_no = dbo.pi_employee.emp_no
LEFT OUTER JOIN
dbo.pi_jobtitlehist ON dbo.pi_employee.emp_no = dbo.pi_jobtitlehist.emp_no ON
dbo.pi_location.loc_id = dbo.pi_employee.emp_location_id
LEFT OUTER JOIN
dbo.pi_salgrade ON dbo.pi_employee.emp_salgrade_id = dbo.pi_salgrade.salgrade_id
LEFT OUTER JOIN
dbo.tbl_emp_status ON dbo.pi_employee.emp_status = dbo.tbl_emp_status.StatusID
LEFT OUTER JOIN
dbo.pi_skills ON dbo.pi_employee.emp_no = dbo.pi_skills.emp_no
LEFT OUTER JOIN
dbo.pi_location AS pi_location_1
INNER JOIN
dbo.pi_lochistory ON pi_location_1.loc_id = dbo.pi_lochistory.loc_id ON dbo.pi_employee.emp_no = dbo.pi_lochistory.emp_no
LEFT OUTER JOIN
dbo.pi_education ON dbo.pi_employee.emp_no = dbo.pi_education.emp_no
LEFT OUTER JOIN
dbo.pi_jobtitle AS pi_jobtitle_1 ON dbo.pi_employee.emp_jobtitle_id = pi_jobtitle_1.jobtitle_id
I am writing sql query to implement different scenario, but problem is that it gives repeated values. I write distinct and order by too but result was same can any one help me to solve this issue.
EDIT – The same query with table names aliased:
SELECT
em.emp_firstname, em.emp_lastname,
em.emp_no, em.emp_cnic,
em.emp_currentadd, em.emp_cellph,
em.emp_birthday, jt.jobtitle_name,
em.emp_joindate, ed.edu_degree,
ed.edu_year, em.emp_pension,
em.emp_age, em.emp_service,
em.emp_terminate, em.emp_termdate,
em.emp_basicofpay, em.emp_terminationreason,
em.emp_terminationdate, em.emp_status,
em.emp_gender, em.emp_maritalstatus,
em.emp_paymethod, em.emp_leaveentitle,
em.emp_confirmation, em.emp_title,
em.emp_basicamount, sg.salgrade_name,
es.StatusName, s.skill_type,
L.loc_name, L1.loc_name AS wcity,
jh.jthSaleGradetype, we.exp_serperiod,
em.emp_domicile, s.skill_type AS Skill,
s.skill_exp, ed.edu_degree AS Degree,
ed.edu_uni, ed.edu_distinction,
Lh.lhstart_date, Lh.lhend_date
FROM
dbo.pi_location AS L
RIGHT OUTER JOIN
dbo.pi_workexp AS we
RIGHT OUTER JOIN
dbo.pi_employee AS em ON we.emp_no = em.emp_no
LEFT OUTER JOIN
dbo.pi_jobtitlehist jh ON em.emp_no = jh.emp_no ON L.loc_id = em.emp_location_id
LEFT OUTER JOIN
dbo.pi_salgrade AS sg ON em.emp_salgrade_id = sg.salgrade_id
LEFT OUTER JOIN
dbo.tbl_emp_status AS es ON em.emp_status = es.StatusID
LEFT OUTER JOIN
dbo.pi_skills AS s ON em.emp_no = s.emp_no
LEFT OUTER JOIN
dbo.pi_location AS L1
INNER JOIN
dbo.pi_lochistory AS Lh ON L1.loc_id = Lh.loc_id ON em.emp_no = Lh.emp_no
LEFT OUTER JOIN
dbo.pi_education ed ON em.emp_no = ed.emp_no
LEFT OUTER JOIN
dbo.pi_jobtitle AS j ON em.emp_jobtitle_id = j.jobtitle_id
Yeah, since you're doing a crap ton of Cartesian products with those joins without on clauses, that will cause plenty of what seem like 'repeated values', but are really just the product of the two tables combining sets.