LEFT JOIN two columns from one table on two separate tables - mysql

I'm not sure if this is possible exactly as stated in the title, but what I'm trying to accomplish, however possible, is what would amount to left joining two columns from one table, each on a separate table.
Here's the statement I'm working with. Unfortunately, MySQL doesn't allow me to actually do this and gives me an error message. Is there another way to accomplish what I want? Is my syntax perhaps just off?
select h.HITTER_ID, u.UMPIRE_ID, u.HAND_B
from
hitters h,
schedules sched
LEFT JOIN
umpires u
ON sched.home_base_umpire_id = u.UMPIRE_ID and h.HAND_B = u.HAND_B
In the umpires table, each UMPIRE_ID appears twice, once with HAND_B = "R" and once with HAND_B = "L"
Essentially, I want to:
1) Pull the UMPIRE_ID from umpires when that UMPIRE_ID appears in schedules
2) Of the two UMPIRE_ID records, select the one with the HAND_B field that corresponds to the HAND_B field in hitters
I could put the "h.HAND_B = u.HAND_B" in the where clause, but that would require that the UMPIRE_ID not be NULL, and I need to leave open the possibility that it is NULL.
How can I accomplish this?

You need to modify your query to be like below
select h.HITTER_ID,
u.UMPIRE_ID,
u.HAND_B
from hitters h
left join umpires u on h.HAND_B = u.HAND_B
left join schedules sched ON sched.home_base_umpire_id = u.UMPIRE_ID;

Related

MySQL JOIN to return correct value from secondary table

I'm joining two tables together, a "Photos" table and "Locations" table. Each location may or may not have a default picture associated with it, and if it does I want to return that photo name. If it doesn't then return null. The default image for each location (if it exists) is always the image that has the "PictureSort" value of 1.
From my first SQL attempt below, if I use a WHERE statement, then I don't receive the null locations (where photos don't exist for that location).
SELECT a.LocationID, a.LocationName, b.PictureSort, b.PictureName
FROM Locations AS a
LEFT JOIN Photos AS b ON a.LocationID = b.LocationID
WHERE b.PictureSort = '1'
GROUP BY a.LocationID
I also tried using the MIN() function in mySQL to say show me the lowest value in the PictureSort column, and while that works for that column, the column right next to it PictureName doesn't follow suit and return the associated value to the PictureSort column.
SELECT a.LocationID, a.LocationName, MIN(b.PictureSort) AS PictureSort, b.PictureName
FROM Locations AS a
LEFT JOIN Photos AS b ON a.LocationID = b.LocationID
GROUP BY a.LocationID
Any help is greatly appreciated. I want this to work, but I'm also looking for the least expensive query possible to get this done.
Thanks!
Conditions on the second table should be in the on clause for a left join.
Also, your table aliases should be related to the names of the table. And the GROUP BY should not be needed. So try this:
SELECT l.LocationID, l.LocationName, p.PictureSort, p.PictureName
FROM Locations l LEFT JOIN
Photos p
ON p.LocationID = l.LocationID AND b.PictureSort = '1';
If PictureSort is stored as a number, then drop the single quotes. Don't mix data types.

Retrieving uniq records with union in mysql

I have two tables usersin and usersout(I can not change schema, a lot of system changes must be done in php otherwise). I should get all user records in a query but I should mark them if they are in or out also a user may have an in record and out record I shouldn't show in record if has an out record.
I have created tables with sample data in SQL Fiddle: http://www.sqlfiddle.com/#!9/ac99a/1/0
Can u help me how can I remove duplicates of user records in this union query?
If you want to have all entries with an entry in either the in or out table, but not in both of them, then a full outer join would be your friend.
Since MySQL does not know that kind of join, you can emulate it with a left outer join and a right outer join combined like so:
SELECT
ui.id, ui.user, 'i'
FROM
usersIN ui
LEFT OUTER JOIN
usersOUT uo ON ui.user = uo.user
WHERE uo.id IS NULL
UNION
SELECT
uo.id, uo.user, 'o'
FROM
usersIN ui
RIGHT OUTER JOIN
usersOUT uo ON ui.user = uo.user
WHERE ui.id IS NULL;
This should give you the right output.
A good visual explanation of joins can be found here

I can't join multiple tables on SQL

I need to join four tables into one on some conditions, but I only manage to join three of them, even if I do everything exactly the same on the fourth one. Can somebody, please, help me with this issue? It works if I delete the last paragraph, but if I leave it there it says "syntax error in JOIN operation".
SELECT Leidinys, ISSN, Pobudis
FROM ((Leidinio_ID_Leidinys
LEFT JOIN (Leidinio_ID_ISSN_ID
LEFT JOIN ISSN_ID_ISSN
ON Leidinio_ID_ISSN_ID.ISSN_ID = ISSN_ID_ISSN.ISSN_ID)
ON (Leidinio_ID_Leidinys.Leidinio_ID = Leidinio_ID_ISSN_ID.Leidinio_ID))
LEFT JOIN ((Leidinio_ID_Pobudzio_ID
LEFT JOIN Pobudzio_ID_Pobudis
ON Leidinio_ID_Pobudzio_ID.Pobudzio_ID = Pobudzio_ID_Pobudis.Pobudzio_ID))
ON (Leidinio_ID_Leidinys.Leidinio_ID = Leidinio_ID_Pobudzio_ID.Leidinio_ID))
LEFT JOIN ((Leidinio_ID_Metai_ID
LEFT JOIN Metai_ID_Prieigos_Metai
ON Leidinio_ID_Metai_ID.Metai_ID = Metai_ID_Prieigos_Metai.Metai_ID)
ON (Leidinio_ID_Leidinys.Leidinio_ID = Leidinio_ID_Metai_ID.Leidinio_ID))
your parens are out of sync i bet
you need the first parens after first FROM to enclose all 3 "left joins" clauses, so you need to
1) copy to clipboard then remove the last "left join clause"
2) insert the copied code in front of the very last parens
this is my best guess based on the info provided, good luck
Not a complete answer but a pointer the table names are so similar to each other and also they r not in english so struggling a bit , but here is something you need to do .
JOIN between two table at one time and then mention their joining condition in ON clause
SELECT Leidinys, ISSN, Pobudis
FROM Leidinio_ID_Leidinys LEFT JOIN Leidinio_ID_ISSN_ID --<-- Two Table in JOIN
ON Leidinio_ID_Leidinys.Leidinio_ID = Leidinio_ID_ISSN_ID.Leidinio_ID --<-- Condition on you want to join these table
LEFT JOIN ISSN_ID_ISSN --<-- result set on 1st join, joins with this table
ON Leidinio_ID_ISSN_ID.ISSN_ID = ISSN_ID_ISSN.ISSN_ID --<-- condition on which you want to join the result set and this table ... and so on ....
LEFT JOIN Leidinio_ID_Pobudzio_ID
ON Leidinio_ID_Leidinys.Leidinio_ID = Leidinio_ID_Pobudzio_ID.Leidinio_ID
LEFT JOIN Pobudzio_ID_Pobudis
ON Leidinio_ID_Pobudzio_ID.Pobudzio_ID = Pobudzio_ID_Pobudis.Pobudzio_ID
.
...... Join with other tables along with their joining conditions and so on.....
Then also in your Select statement you need to mention the TableName.Column name because the column names you have mentioned in your Select statement exists in more then One table you need to tell sql server from which table you need that particular column.

MySQL LEFT JOIN with optional value in second table

I have two tables: projects and user_licenses.
I'd like to grab the entire list of projects from the database, as well as the user's current license state. The licenses table has a user ID field which I check against a $_SESSION variable for the value. The thing is, they might not have a license, or a non-logged in visitor may want to see the projects list. My question is this: How can I get the data from the left table always display, but only grab data for that row from the right table when certain conditions are met?
The query I have at the moment is this:
SELECT Projects.*,
UserLicenses.*
FROM Projects
LEFT JOIN UserLicenses ON Projects.id = UserLicenses.project_id
WHERE UserLicenses.user_id = 12
ORDER BY name ASC
Add any extra conditions to the on clause of the left join. They will only affect the joined table.
SELECT Projects.*,
UserLicenses.*
FROM Projects
LEFT JOIN UserLicenses
ON Projects.id = UserLicenses.project_id
and UserLicenses.user_id = 12
and UserLicences.Question = '6*7'
and UserLicences.Answer = 42
ORDER BY name ASC
This will return projects without matching licenses.
Move the UserLicenses condition away from WHERE, and up to the JOIN condition. By having it in the WHERE part, you will never see those "left" rows because they are filtered away.
You can also probably use WHERE (UserLicenses.user_id = 12 OR UserLicenses.user_id IS NULL)
Don't do that. Just move it to the join condition like this:
LEFT JOIN UserLicenses ON
(Projects.id = UserLicenses.project_id AND UserLicenses.user_id = 12)
You can use LEFT JOIN
If its conditions match then values show otherwise null value shows.

How do I decide when to use right joins/left joins or inner joins Or how to determine which table is on which side?

I know the usage of joins, but sometimes I come across such a situation when I am not able to decide which join will be suitable, a left or right.
Here is the query where I am stuck.
SELECT count(ImageId) as [IndividualRemaining],
userMaster.empName AS ID#,
CONVERT(DATETIME, folderDetails.folderName, 101) AS FolderDate,
batchDetails.batchName AS Batch#,
Client=#ClientName,
TotalInloaded = IsNull(#TotalInloaded,0),
PendingUnassigned = #PendingUnassigned,
InloadedAssigned = IsNull(#TotalAssigned,0),
TotalProcessed = #TotalProcessed,
Remaining = #Remaining
FROM
batchDetails
Left JOIN folderDetails ON batchDetails.folderId = folderDetails.folderId
Left JOIN imageDetails ON batchDetails.batchId = imageDetails.batchId
Left JOIN userMaster ON imageDetails.assignedToUser = userMaster.userId
WHERE folderDetails.ClientId =#ClientID and verifyflag='n'
and folderDetails.FolderName IN (SELECT convert(VARCHAR,Value) FROM dbo.Split(#Output,','))
and userMaster.empName <> 'unused'
GROUP BY userMaster.empName, folderDetails.folderName, batchDetails.batchName
Order BY folderDetails.Foldername asc
Yes, it depends on the situation you are in.
Why use SQL JOIN?
Answer: Use the SQL JOIN whenever multiple tables must be accessed through an SQL SELECT statement and no results should be returned if there is not a match between the JOINed tables.
Reading this original article on The Code Project will help you a lot: Visual Representation of SQL Joins.
Also check this post: SQL SERVER – Better Performance – LEFT JOIN or NOT IN?.
Find original one at: Difference between JOIN and OUTER JOIN in MySQL.
In two sets:
Use a full outer join when you want all the results from both sets.
Use an inner join when you want only the results that appear in both
sets.
Use a left outer join when you want all the results from set a, but
if set b has data relevant to some of set a's records, then you also
want to use that data in the same query too.
Please refer to the following image:
I think what you're looking for is to do a LEFT JOIN starting from the main-table to return all records from the main table regardless if they have valid data in the joined ones (as indicated by the top left 2 circles in the graphic)
JOIN's happen in succession, so if you have 4 tables to join, and you always want all the records from your main table, you need to continue LEFT JOIN throughout, for example:
SELECT * FROM main_table
LEFT JOIN sub_table ON main_table.ID = sub_table.main_table_ID
LEFT JOIN sub_sub_table on main_table.ID = sub_sub_table.main_table_ID
If you INNER JOIN the sub_sub_table, it will immediately shrink your result set down even if you did a LEFT JOIN on the sub_table.
Remember, when doing LEFT JOIN, you need to account for NULL values being returned. Because if no record can be joined with the main_table, a LEFT JOIN forces that field to appear regardless and will contain a NULL. INNER JOIN will obviously just "throw away" the row instead because there's no valid link between the two (no corresponding record based on the ID's you've joined)
However, you mention you have a where statement that filters out the rows you're looking for, so your question on the JOIN's are null & void because that is not your real problem. (This is if I understand your comments correctly)