Query junction table-many to many relationship - sql-server

I'm trying to run a query for a many-many relationship, I created a junction table to do that. Now I'm having issues getting no results when I'm expecting to return 3 rows for each of indexes 122,123,124, can anyone point out my errors, thank you
SELECT * FROM [Moldingdata].[dbo].[mach_part_junction] ORDER BY [machinename] ASC
SELECT MachineList.machinename ,JDEPARTIMGLU.Jde_part_num
from mach_part_junction
INNER JOIN MachineList on mach_part_junction.machinename = machinelist.Machine_ID
INNER JOIN JDEPARTIMGLU on mach_part_junction.machinename = machinelist.Machine_ID
WHERE mach_part_junction.machinename= 'MM01'
Results:
machinename ndx_jde_part_img
----------- ----------------
MM01 122
MM01 123
MM01 124
MM04 122
MM15 124
MM17 122
MM32 122
MM32 123
(8 row(s) affected)
machinename Jde_part_num
----------- --------------------
(0 row(s) affected)

The join conditions on your second and third table are the same.
It looks like the third table's join condition is the one that needs to be changed.

When I troubleshoot queries like this I generally do the following:
SELECT *
FROM mach_part_junction
INNER JOIN MachineList on mach_part_junction.machinename = machinelist.Machine_ID
Then I add the next JOIN:
SELECT *
FROM mach_part_junction
INNER JOIN MachineList on mach_part_junction.machinename = machinelist.Machine_ID
INNER JOIN JDEPARTIMGLU on mach_part_junction.machinename = machinelist.Machine_ID
then the WHERE (if the tables aren't too big)
That way you can see what's going on.

Related

How to use multi-column sql query result as input for new query

An alternative title would be "how to join two external tables with two different values, by row, from query result". I'm open to suggestions/edits.
I have this query result (2 of 6000+ lines shown)
objectpriref packpriref locpriref
------------ ---------- ----------
30889 229 16672
30990 267 16697
and 2 tables like this
objname location
id name id name
---------.-------- ---------.----
30889 MACQ_001 16672 A16
30890 BLAH_002 16673 A17
30990 FOOH_009 16697 B300
The desired result should look something like this
objectpriref objname locname
------------ ---------- ----------
30889 MACQ_001 A16
30990 FOOH_009 B300
If this can be done within SQL, what would be the best approach? What I've tried so far:
Put the query result into a temp table using INTO #mtt (for MyTempTable) from here and then trying to address the various columns as #mtt.objectpriref etc. This gets me invalid object name #mtt. This might deserve a separate question.
Put the query inside another select, but that runs into this, using IN works on single columns only.
I may be using the wrong keywords to google for. Any suggestions?
Something like
select
T1.objectpriref,
T2.name as objname,
T3.name as locname
from
table1 T1
inner join table2 T2
on T2.objnameid = T1.objectpriref
inner join table3 T3
on T3.locationid = T1.locpriref
Try this with your table names.
select t1.objectpreiref, t2.name, t3.name
from table1 t1
left join table2 t2 on t1.objectpriref = t2.objnameid
left join table3 t3 on t1.locpriref = t3.locationid

Select records when 2 column's data will match

I have two tables as shown below:
-----------------------
|EmpNo|Complaint |
-----------------------
|9091 |Change required|
|9092 |No change |
|9093 |Changes done |
-----------------------
Above table contains employee number and his complaints.
I have one another table which contains employee all kind of details as shown below.
-------------------------------
|EmpNo|EmailID |EmpBossNO|
-------------------------------
|9091 |abc#gmail.com|9092 |
|9092 |xyz#gmail.com|9093 |
|9093 |mno#gmail.com|9099 |
-------------------------------
Here, if Empno:9091 will raise any complain then a mail will send to his boss that the complain is raise by your employee and you have to accept it so I want to get EmailID of employee's boss and for that I want one SQL query. I tried the query shown here, but it doesn't work.
select EmpEmailID
from tblComplaint
inner join tblEmpMaster on tblEmpMaster.EmpNo = tblComplaint.EmpPSNo
where tblComplaint.EmpPSNo = tblEmpMaster.EmpBossNo
I want output like.. if complaint is raised by EmpNo:9091 then it will return EmailID of his boss which is xyz#gmail.com.
You are on the right track with a join between the tblComplaint and tblEmpMaster tables. But, you need an additional join to tblEmpMaster to bring in the boss' email for each employee complaint.
SELECT
c.EmpNo,
c.Complaint,
COALESCE(e2.EmailID, 'NA') AS boss_email
FROM tblComplaint c
INNER JOIN tblEmpMaster e1
ON c.EmpNo = e1.empNo
LEFT JOIN tblEmpMaster e2
ON e1.EmpBossNO = e2.EmpNo;
Demo
I used a left self join above, in case a given employee does not have a boss (e.g. for the highest ranking boss). In this case, I display NA for the boss email.
You should self join tblEmpMaster
select boss.EmpEmailID
from tblComplaint
inner join tblEmpMaster emp on emp.EmpNo = tblComplaint.EmpPSNo
inner join tblEmpMaster boss on boss.EmpNo = emp.EmpBossNO
where tblComplaint.EmpPSNo = 9091
DB Fiddle
you can even use sub queries to get the Email_Id of the boss as shown below
SELECT Email_Id
FROM EMP_Details
WHERE Emp_No IN (
SELECT Boss_Id
FROM Emp_Details) AND
Emp_No IN (
SELECT Emp_No
FROM Emp_Complaints)

SQL Join Including NULLs

Using SQL Server Management Studio 2016 (v 13.0).
I have two tables with two distinct keys I can use to join, with the catch being that there are mixed NULLs in both PK columns:
Table 1 Table 2
Acct1 App1 Acct2 App2 Product
----------- ----------------------
1 A NULL A Bed
2 B 2 B Sofa
3 C 3 NULL Bed
4 D 4 D Bed
Desired result in the joined table, only including those where Product = Bed:
Acct App Product
1 A Bed
3 C Bed
4 D Bed
Thank you!
While I agree #d219's answer should be the correct solution, a different approach could use an or in the join such like:
select Acct1,App1,Product
from table1 inner join table2
on App1=App2 or Acct1=Acct2
where Product='Bed'
See this post for discussion on using the or join.
One way would be to do two separate SELECT statements using each key and then UNION them, something like this:
SELECT t1.Acct1, t1.App1, t2.Product
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.Acct1 = t2.Acct2
WHERE t2.Product = 'Bed'
UNION
SELECT t1.Acct1, t1.App1, t2.Product
FROM Table1 t1
INNER JOIN Table2 t2
ON t1.App1 = t2.App2
WHERE t2.Product = 'Bed'

Insert using Insert Into and Inner Join

I'm inserting rows of data from one table's column to another table's column. This is my work done:
Insert into [Inventory](Cost)
Select cast(a.[CCost] as numeric(18,6)) from [InventoryTemp] as a
Inner join [Inventory] as b on a.[ID] = b.[ID]
I have 10000 rows of data in my [Inventory] table (ID column is filled up) but when the above query was executed, the Cost data started from 10001 until 20000.
Inventory InventoryTemp
ID Cost ID Cost
1 1 3.12
3 3 9.90
18 18 8.80
The result I want
Inventory
ID Cost
1 3.12
3 9.90
18 8.80
If I have read your question correctly, I think you are trying to update the values of the cost column in your Inventory table, based on the values in the InventoryTemp table.
Therefore you want to perform an UPDATE command rather than an INSERT.
An example of this would be:
UPDATE
Inventory
SET
Inventory.Cost = InventoryTemp.Cost
FROM
Inventory
INNER JOIN
InventoryTemp
ON
Inventory.ID = InventoryTemp.ID
For more info please see this question: How do I UPDATE from a SELECT in SQL Server?
You need to use UPDATE instead of `INSERT'
UPDATE i
SET [Cost] = it.[Cost]
FROM [Inventory] i
INNER JOIN [InventoryTemp] it
ON i.ID = it.ID
Try use update.
UPDATE b
SET b.Cost = a.Cost
FROM
[InventoryTemp] as a
Inner join [Inventory] as b on a.[ID] = b.[ID]

Need help implementing a Full Outer Join in MS Access

I'm having trouble getting a query to work properly in Access. I need a full outer join on dbo_cardpurchases and dbo_vendors so that all all vendors will appear in the query regardless of whether a purchase was made at that vendor. But Access doesn't support full outer joins. How else can I do this?
SELECT dbo_vendors.name,
Iif([fundingsourceid] = 10, [amount], "") AS Credit,
Iif(( [fundingsourceid] = 2 )
OR ( [fundingsourceid] = 3 ), [amount], "") AS EBT,
Iif([fundingsourceid] = 4, [amount], "") AS [Match],
dbo_cardpurchases.updateddate,
dbo_markets.marketid
FROM (((dbo_cardpurchases
LEFT JOIN dbo_vendors
ON dbo_cardpurchases.vendorid = dbo_vendors.vendorid)
LEFT JOIN dbo_cardfundings
ON dbo_cardpurchases.cardfundingid =
dbo_cardfundings.cardfundingid)
INNER JOIN dbo_marketevents
ON dbo_cardpurchases.marketeventid =
dbo_marketevents.marketeventid)
INNER JOIN dbo_markets
ON dbo_marketevents.marketid = dbo_markets.marketid
ORDER BY dbo_vendors.name;
As mentioned in the Wikipedia article on joins here, for sample tables
[employee]
LastName DepartmentID
---------- ------------
Heisenberg 33
Jones 33
Rafferty 31
Robinson 34
Smith 34
Williams NULL
and [department]
DepartmentID DepartmentName
------------ --------------
31 Sales
33 Engineering
34 Clerical
35 Marketing
the full outer join
SELECT *
FROM employee FULL OUTER JOIN department
ON employee.DepartmentID = department.DepartmentID;
can be emulated using a UNION ALL of three SELECT statements. So, in Access you could do
SELECT dbo_employee.LastName, dbo_employee.DepartmentID,
dbo_department.DepartmentName, dbo_department.DepartmentID
FROM dbo_employee
INNER JOIN dbo_department ON dbo_employee.DepartmentID = dbo_department.DepartmentID
UNION ALL
SELECT dbo_employee.LastName, dbo_employee.DepartmentID,
NULL, NULL
FROM dbo_employee
WHERE NOT EXISTS (
SELECT * FROM dbo_department
WHERE dbo_employee.DepartmentID = dbo_department.DepartmentID)
UNION ALL
SELECT NULL, NULL,
dbo_department.DepartmentName, dbo_department.DepartmentID
FROM dbo_department
WHERE NOT EXISTS (
SELECT * FROM dbo_employee
WHERE dbo_employee.DepartmentID = dbo_department.DepartmentID)
However, since you are using linked tables into SQL Server you can just use an Access pass-through query and perform a "real" FULL OUTER JOIN using T-SQL:
Pass-through queries always produce recordsets that are not updateable, but a native Access query against linked tables that uses UNION ALL is going to produce a recordset that is not updatable anyway, so why not take advantage of the speed and simplicity of just using SQL Server to run the query?

Resources