I am using sql to create a custom ODBC query into Excel.
I have 2 tables 'TBL_CONTACT' and 'TBL_ADDRESS' that I want to INNER JOIN on 'contactid', which is a column that exists in both.
This works fine if I select all columns, but stops working if I start defining the columns I want to show.
Working code:
SELECT * FROM "TBL_CONTACT" AS CONTACT
INNER JOIN (SELECT * FROM "TBL_ADDRESS" AS ADDRESS) ADDRESS
ON CONTACT.contactid = ADDRESS.contactid
Non-working code:
SELECT CONTACT.contactid, CONTACT.fullname FROM "TBL_CONTACT" AS CONTACT
INNER JOIN (SELECT * FROM "TBL_ADDRESS" AS ADDRESS) ADDRESS
ON CONTACT.contactid = ADDRESS.contactid
This only shows the 'contactid' and 'fullname' columns from 'TBL_CONTACT' and doesn't join anything from 'TBL_ADDRESS'.
EXAMPLE:
TBL_CONTACT
contactid firstname fullname
1001 John John Smith
1002 Tom Tom Adams
TBL_ADDRESS
contactid line1 line2 postcode
1001 3 Farm Ln Essex AB1 1BA
1002 1 Tim st Kent CN2 2NC
Desired result:
contactid fullname contactid2 line1 line2 postcode
1001 John Smith 1001 3 Farm Ln Essex AB1 1BA
1002 Tom Adams 1002 1 Tim st Kent CN2 2NC
1st code gives following result:
contactid firstname fullname contactid2 line1 line2 postcode
1001 John John Smith 1001 3 Farm Ln Essex AB1 1BA
1002 Tom Tom Adams 1002 1 Tim st Kent CN2 2NC
2nd code gives following result:
contactid fullname
1001 John Smith
1002 Tom Adams
I'm fairly new to SQL but am not sure what i'm doing wrong here. Any help would be greatly appreciated!
Joining a table results in the columns being available for your select. When you select all columns (with * like in your first code snippet) the columns of your joined table will be selected, too. However, when manually selecting columns, you have to define which columns you want from your joined table, too.
Let's say you want to have the 2 columns contactid and fullname from your Table TBL_CONTACT and all columns from the joined table TBL_ADDRESS:
SELECT `TBL_CONTACT`.`contactid`, `TBL_CONTACT`.`fullname`, `TBL_ADDRESS`.* FROM TBL_CONTACT
INNER JOIN TBL_ADDRESS
ON `TBL_CONTACT`.`contactid` = `TBL_ADDRESS`.`contactid`
Backticks are optional.
Alternatively, you could specify columns for the joined table, too.
Try this
//MySQL
SELECT TC.contactid,TC.fullname,TA.`address_table_column`
FROM TBL_CONTACT TC
INNER JOIN TBL_ADDRESS TA
ON TC.contactid = TA.contactid
//SQL Server
SELECT TC.contactid,TC.fullname,TA.[address_table_column]
FROM TBL_CONTACT TC
INNER JOIN TBL_ADDRESS TA
ON TC.contactid = TA.contactid
Wnen you have joined multiple tables and you select some field you must specify
to which table the field belongs .
Because like in your case the same field can be in both tables and then mysql does not know which one to fetch.
So just use the table prefix in your query and of course SELECT all the fields you want:
SELECT `TBL_CONTACT`.`contactid`,`TBL_CONTACT`.`fullname`,`TBL_ADDRESS`.`contactid` as contactid2,`TBL_ADDRESS`.`line1`,`TBL_ADDRESS`.`line2`,`TBL_ADDRESS`.`postcode` FROM `TBL_CONTACT`
INNER JOIN `TBL_ADDRESS`
ON `TBL_CONTACT`.`contactid` = `TBL_ADDRESS`.`contactid`
SELECT contact.*, ADDRESS.* FROM "TBL_CONTACT" contact INNER JOIN "TBL_ADDRESS" ADDRESS ON contact.contactid = ADDRESS.contactid;
Related
I need to find the firstName and Email address from of all teachers and parents in a single query
Here is the structure of the table :
// Patients Table
ID guid parentID PatientName
1 234 1258 John
2 xyz 111 Paul
// Patient_teacher table
ID PatiendGuid teacherid
1 122 132
2 xyz 1424
3 245 1545
4 xyz 1222
// Members table
ID guid email fname
22 123 hello#xyz.com hello
111 xyz parentEmail#xyz.com parentName
1424 343 teacherEmail#xyz.com teacherName
1222 546 teacher2EMail#xyz.com teacher2Name
And Here is the required Result:
//Required Result
fname Email
parentName parentEmail#xyz.com
techerName teacherEmail#xyz.com
teacher2Name teacher2Email#xyz.com
The problem is when I tried to search using join I found a single row that contains parentID and TeacherID
Here is what I tried:
select Members.email,Members.fname
from Members
join Patients on Members.guid = Patients.guid
join Patient_Teacher on Patient_Teacher.patientguid = Patients.guid
where patients.guid = 'xyz'
Here is the Solution :
select Members.id, Members.email, Members.fname
from Patients
join Patient_Teacher on Patient_Teacher.patientguid = Patients.guid
join Members on (Patient_Teacher.teacherid = Members.id
or Patients.parent = Members.id)
where patients.guid = 'xyz'
Have you checked the following reasons?
1- You have a table named 'Patients_teacher' but in your solution, you're referring to it as 'Patient_teacher'.
2- In 'Patients_teacher' table, you have a column named 'patiendguid' but in your solution you're referring to it as 'patientguid'.
Simple Database:
street | age
1st st | 2
2nd st | 3
3rd st | 4
3rd st | 2
I'd like to build a query that'll return the DISTINCT street names, but only for those households where no one is over 3.
so that result would be:
street | age
1st st | 2
2nd st | 3
How do I do that? I know of DISTINCT, but now how to conditionalize it for all the records that match the DISTINCT
Suppose the name of the table is 'tab'. You can then try:
select distinct street from tab where street not in (select street from tab where age>3);
I have created a sql fiddle where you can view the result:
http://sqlfiddle.com/#!9/2c513d/2
Distinct street names for households where no one is over 3:
SELECT street
FROM table
GROUP BY street
HAVING COUNT(1) <= 3
SELECT DISTINCT street
FROM table
WHERE NOT(age>3)
USE GROUP BY
Select Street
from yourtable
group by street
Having sum(age)<=3
Another way this could be achived with a use of NOT EXISTS
SELECT *
FROM yourtable a
WHERE NOT EXISTS
(SELECT street
FROM yourtable b
WHERE age > 3
AND a.street = b.street)
I have 2 tables respectively,emp_data, role_data
EMP_DATA
ID EMPID EMPNAME ROLEID
1 A01 ABC 1
2 A01 ABC 3
ROLE_DATA
ROLEID ROLENAME EMPID
1 SE A01
2 SSE B01
When I join these 2 tables, i have to get OUTPUT OF 2 records like the below one
EMPID EMPNAME ROLEID ROLENAME
A01 ABC 1 SE
A01 ABC 3 <NULL OR EMPTY>
The query what i have written will give output where instead of null in rolename it gives me SE.
SELECT ED.EMPID,ED.EMPNAME,ED.ROLEID,RD.ROLENAME
FROM SYN.EMP_DATA ED,SYN.ROLE_DATA RD
WHERE ED.EMPID=RD.EMPID
Kindly help me in this regard as to how to get the output like i desire.
Thanks in advance
You want a left join:
select e.EMPID, e.EMPNAME, e.ROLEID, r.ROLENAME
from EMP_DATA e left join
ROLE_DATA r
on e.ROLEID = r.ROLEID;
By the way, your problem suggests an issue with your database. EMP_DATA.ROLEID should be declared as a foreign key referencing ROLE_DATA. If so, it would be an error to insert a value that is invalid.
Show us your code. You have to use LEFT JOIN
SELECT emp.EMPID
,emp.EMPNAME
,emp.ROLEID
,ROLE.ROLENAME
FROM EMP_DATA as emp
LEFT JOIN ROLE_DATA as ROLE ON emp.ROLEID = ROLE.ROLEID;
Try this query
select a.EMPID, a.EMPNAME, a.ROLEID,IFNULL(b.ROLENAME, 'SE') as ROLENAME
from EMP_DATA a
lef join ROLE_DATA b on a.ROLEID=B.ROLEID
If I have a table...
ID Name Manager
0 Joe Sue
1 Jake Tom
0 Joe Tom
2 Larry Red
2 Larry Paul
1 Jake Paul
I want the output to be....
ID Name Manager1 Manager2
0 Joe Sue Tom
1 Jake Tom Paul
2 Larry Red Paul
Thanks...
If I have understood your request properly, yes, something like would produce the results you are looking for.
SELECT
t1.Name Name,
t1.Manager Manager1,
t2.Manager Manager2
FROM
Table t1
inner join Table t2 on t1.Manager = t2.Name
Of course a foreign key back to the index column would be preferential to strong comparisons for performance.
Yeah, if your table was called 'Managers':
SELECT Mgr1.ID,Mgr1.Name,Mgr1.Manager,Mgr2.Manager
FROM Managers AS Mgr1
LEFT JOIN Managers AS Mgr2
ON Mgr1.ID=Mgr2.ID
If your keeping the tables a join would be best.
If you hate joins, you could combine the max and min managers, and even then it would work if there is always 2 managers and they can't have the same name.
The below should work if I remember how to join up 2 queries correctly. but i would advise to see if it is possible to rework your table, have a separate table linking people to each other in a manager employee relation.
SELECT DISTINCT
F.ID, F.Name, S.Manager, F.Manager
FROM
(SELECT
ID, Name, MIN(manager) manager
FROM Managers
GROUP BY ID, Name) F,
(SELECT
ID, Name, MAX(manager) manager
FROM Managers
GROUP BY ID, Name) S
WHERE
F.ID = S.ID
AND S.Manager <> F.Manager
AND F.ID < S.ID
I have got a table named student. I have written this query:
select * From student where sname in ('rajesh','rohit','rajesh')
In the above query it's returning me two records; one matching 'rajesh' and another matching: 'rohit'.
But i want there to be 3 records: 2 for 'rajesh' and 1 for 'rohit'.
Please provide me some solution or tell me where i am missing.
NOTE: the count of result of sub query is not fix there can be many words there some distinct and some multiple occurrence .
Thanks
Your requirements are not clear, and I'll try to explain why.
Let's define table students
ID FirstName LastName
1 John Smith
2 Mike Smith
3 Ben Bray
4 John Bray
5 John Smith
6 Bill Lynch
7 Bill Smith
Query with WHERE clause:
FirstName in ('Mike', 'Ben', 'Mike')
will return 2 rows only, because it could be rewritten as:
FirstName='Mike' or FirstName='Ben' or FirstName='Mike'
WHERE is filtering clause that just says if existing row satisfy given conditions or not (for each of rows created by FROM clause.
Let's say we have subquery that returns any number of non distinct FirstNames
In case if SQ contains 'Mike', 'Ben', 'Mike' using inner join you can get those 3 rows without problem
Select ST.* from Students ST
Inner Join (Select name from …. <your subquery>) SQ
On ST.FirstName=SQ.name
Result will be:
ID FirstName LastName
2 Mike Smith
2 Mike Smith
3 Ben Bray
Note data are not ordered by order of names returning by SQ. If you want that, SQ should return some ordering number, eg.:
Ord Name
1. Mike
2. Ben
3. Mike
In that case query should be:
Select ST.* from Students ST
Inner Join (Select ord, name from …. <your subquery>) SQ
On ST.FirstName=SQ.name
Order By SQ.ord
And result:
ID FirstName LastName
2 Mike Smith (1)
3 Ben Bray (2)
2 Mike Smith (3)
Now, let's se what will happen if subquery returns
Ord Name
1. Mike
2. Bill
3. Mike
You will end up with
ID FirstName LastName
2 Mike Smith (1)
6 Bill Lynch (2)
7 Bill Smith (2)
2 Mike Smith (3)
Even worse, if you have something like:
Ord Name
1. John
2. Bill
3. John
Result is:
ID FirstName LastName
1 John Smith (1)
4 John Bray (1)
5 John Smith (1)
6 Bill Lynch (2)
7 Bill Smith (2)
1 John Smith (3)
4 John Bray (3)
5 John Smith (3)
This is an complex situation, and you have to clarify precisely what requirement is.
If you need only one student with the same name, for each of rows in SQ, you can use something like SQL 2005+):
;With st1 as
(
Select Row_Number() over (Partition by SQ.ord Order By ID) as rowNum,
ST.ID,
ST.FirstName,
ST.LastName,
SQ.ord
from Students ST
Inner Join (Select ord, name from …. <your subquery>) SQ
On ST.FirstName=SQ.name
)
Select ID, FirstName, LastName
From st1
Where rowNum=1 -- that was missing row, added later
Order By ord
It will return (for SQ values John, Bill, John)
ID FirstName LastName
1 John Smith (1)
6 Bill Lynch (2)
1 John Smith (3)
Note, numbers (1),(2),(3) are shown to display value of ord although they are not returned by query.
If you can split the where clause in your calling code, you could perform a UNION ALL on each clause.
SELECT * FROM Student WHERE sname = 'rajesh'
UNION ALL SELECT * FROM Student WHERE sname = 'rohit'
UNION ALL SELECT * FROM Student WHERE sname = 'rajesh'
Try using a JOIN:
SELECT ...
FROM Student s
INNER JOIN (
SELECT 'rajesh' AS sname
UNION ALL
SELECT 'rohit'
UNION ALL
SELECT 'rajesh') t ON s.sname = t.sname
just because you've got a criteria in there two times doesn't mean that it will return 1 result per criteria. SQL engines usually just use the unique criteria - thus, from your example, there will be 2 criteria in IN clause: 'rajesh','rohit'
WHY do you need to return 2 results? are there two rajesh in your table? they should BOTH return then. You don't need to ask for rajesh twice for that to happen. What does your data look like? What do you want to see returned?
Hi i am query just as you give above and it give me all data that matches in the condition of in clause. just like your post
select * from person
where personid in (
'Carson','Kim','Carson'
)
order by FirstName
and its give me all records which fulfill this Criteria