LEFT JOIN on multiple tables in "FROM" part - mysql

I'm unable to find an exact example on stackoverflow, so here is my problem. In MySQL 4.x it works fine, but 5.x seems not to like the following:
SELECT some stuff..
FROM schools, member , applications
LEFT JOIN courses ON courses.id = applications.course_id
LEFT JOIN staff ON staff.id=member.staff_id
This section throws up an error saying "Unknown column 'member.staff_id' in 'on clause'". How do I change this so that 5.x won't complain?
EDIT: I did notice that when using 'ONE' LEFT JOIN, it did matter where the table name was placed in the FROM part, ie it has to be at the end. Not sure this has any relevance to the problem though. This is only an issue with 5.x

According to the official MySQL doco, the precedence of the join operator is higher than that of the , (comma) operator. This will cause your joins to be evaluated without the member table, meaning member is not available in the join. However because the applications table is the last in your series of comma delineated tables, it IS available to the joins. MySQL effectively sees the tables like this: (schools, member, (applications left join courses ... ))
13.2.8.2 JOIN Syntax
However, the precedence of the comma operator is less than of INNER
JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with
the other join types when there is a join condition, an error of the
form Unknown column 'col_name' in 'on clause' may occur.
The reason you are encountering this error now, whereas you were able to do it before, is (from the same link)
Previously, the comma operator (,) and JOIN both had the same precedence.
To get around this order of operations limitation, you can either rewrite your query using explicit join syntax only, or you can force the grouping of your comma separated tables by surrounding them with parenthesis, which will make MySQL see your tables more like this ( (schools, member, applications) left join courses ... )
SELECT some stuff..
FROM (schools, member , applications)
LEFT JOIN courses ON courses.id = applications.course_id
LEFT JOIN staff ON staff.id=member.staff_id
But i'd still recommend using explicit join syntax.
select some stuff..
from schools
join member
join applications
left join courses on courses.id = applications.course_id
left join staff on staff.id = member.staff_id

Your edit helped. MySQL doesn't seem to like like that you are mixing the old-style comma separated join syntax with the newer ANSI SQL-92 join syntax.
I would rewrite it as
SELECT some stuff..
FROM schools
JOIN member ON (...)
JOIN applications ON (...)
LEFT JOIN courses ON courses.id = applications.course_id
LEFT JOIN staff ON staff.id=member.staff_id
You will probably have to move some conditions up from your WHERE clause.

Related

Create a query to determine which sub_genres come from which regions

SELECT Sub_Genre.sgid, Sub_Genre.sgname, Region.rname
FROM Sub_Genre AS S, Region AS R
JOIN Band_Styles AS bSty ON bSty.sgname=S.sgname
JOIN Band_Origins AS bOri ON bOri.bname=bSty.bname
JOIN Country AS C ON C.cname=bOri.cname
JOIN Region ON R.rname=C.rname
ORDER BY S.sgid;
I am trying to Create a query to determine which sub_genres come from which regions.
I keep getting an Error Code 1054. Unknown column 'Sub_Genre.sgid' in 'field list'
Don't mix explicit and implicit joins. Use standard, explicit joins consistently.
Table region appears twice in the query, first in an implicit join with an alias, and then in a standard join without an alias. This is most likely not what you want.
Columns in the select clause are prefixed with the entire table name, while the table are aliased in the from clause: this is not supported.
This would be a cleaner way to express the logic:
select s.sgid, s.sgname, r.rname
from sub_genre s
join band_styles bsty on bsty.sgname = s.sgname
join band_origins bori on bori.bname = bsty.bname
join country c on c.cname = bori.cname
join region r on r.rname = c.rname
order by s.sgid;
This fixes the syntax problems. Whether this gives the correct results or not is something else: you did not share the structures and data you are working with, so I cannot tell.

Difference between FROM and JOIN tables

I'm working through the JOIN tutorial on SQL zoo.
Let's say I'm about to execute the code below:
SELECT a.stadium, COUNT(g.matchid)
FROM game a
JOIN goal g
ON g.matchid = a.id
GROUP BY a.stadium
As it happens, it produces the same output as the code below:
SELECT a.stadium, COUNT(g.matchid)
FROM goal g
JOIN game a
ON g.matchid = a.id
GROUP BY a.stadium
So then, when does it matter which table you assign at FROM and which one you assign at JOIN?
When you are using an INNER JOIN like you are here, the order doesn't matter. That is because you are connecting two tables on a common index, so the order in which you use them is up to you. You should pick an order that is most logical to you, and easiest to read. A habit of mine is to put the table I'm selecting from first. In your case, you're selecting information about a stadium, which comes from the game table, so my preference would be to put that first.
In other joins, however, such as LEFT OUTER JOIN and RIGHT OUTER JOIN the order will matter. That is because these joins will select all rows from one table. Consider for example I have a table for Students and a table for Projects. They can exist independently, some students may have an associated project, but not all will.
If I want to get all students and project information while still seeing students without projects, I need a LEFT JOIN:
SELECT s.name, p.project
FROM student s
LEFT JOIN project p ON p.student_id = s.id;
Note here, that the LEFT JOIN refers to the table in the FROM clause, so that means ALL of students were being selected. This also means that p.project will be null for some rows. Order matters here.
If I took the same concept with a RIGHT JOIN, it will select all rows from the table in the join clause. So if I changed the query to this:
SELECT s.name, p.project
FROM student s
RIGHT JOIN project p ON p.student_id = s.id;
This will return all rows from the project table, regardless of whether or not it has a match for students. This means that in some rows, s.name will be null. Similar to the first example, because I've made project the outer joined table, p.project will never be null (assuming it isn't in the original table). In the first example, s.name should never be null.
In the case of outer joins, order will matter. Thankfully, you can think intuitively with LEFT and RIGHT joins. A left join will return all rows in the table to the left of that statement, while a right join returns all rows from the right of that statement. Take this as a rule of thumb, but be careful. You might want to develop a pattern to be consistent with yourself, as I mentioned earlier, so these queries are easier for you to understand later on.
When you only JOIN 2 tables, usually the order does not matter: MySQL scans the tables in the optimal order.
When you scan more than 2 tables, the order could matter:
SELECT ...
FROM a
JOIN b ON ...
JOIN c ON ...
Also, MySQL tries to scan the tables in the fastest way (large tables first). But if a join is slow, it is possible that MySQL is scanning them in a non-optimal order. You can verify this with EXPLAIN. In this case, you can force the join order by adding the STRAIGHT_JOIN keyword.
The order doesn't always matter, I usually just order it in a way that makes sense to someone reading your query.
Sometime order does matter. Try it with LEFT JOIN and RIGHT JOIN.
In this instance you are using an INNER JOIN, if you're expecting a match on a common ID or foreign key, it probably doesn't matter too much.
You would however need to specify the tables the correct way round if you were performing an OUTER JOIN, as not all records in this type of join are guaranteed to match via the same field.
yes, it will matter when you will user another join LEFT JOIN, RIGHT JOIN
currently You are using NATURAL JOIN that is return all tables related data, if JOIN table row not match then it will exclude row from result
If you use LEFT / RIGHT {OUTER} join then result will be different, follow this link for more detail

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.

In my MySQL what is the difference between using the word JOIN or using: table1.id=table2.id

In my MySQL what is the difference between using the word JOIN or using: table1.id=table2.id
Table 1
id name
1 John Lennon
Table 2
id position
1 Singer
//What is the difference then calling JOIN?
Select name, position
From Table1, Table2
Where Table1.id=Table2.id;
There is none as long as there are only two tables. When there are more, you might get different JOIN order than expected, if you use comma to separate tables.
From manual:
INNER JOIN and , (comma) are semantically equivalent in the absence of
a join condition: both produce a Cartesian product between the
specified tables (that is, each and every row in the first table is
joined to each and every row in the second table).
However, the precedence of the comma operator is less than of INNER
JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with
the other join types when there is a join condition, an error of the
form Unknown column 'col_name' in 'on clause' may occur. Information
about dealing with this problem is given later in this section.
If this case, there's no difference.
But the joins can also be: INNER, OUTER (left outer, right outer, full outer joins), LEFT, RIGHT.
Using a JOIN is known as an "explicit join", or an ANSI join... separating your tables with a comma and then linking them in the WHERE clause is known as an "implicit join".
The ANSI join is widely considered to be the preferred syntax. It is easier to follow, less ambiguous, and more consistent when you need to start adding outer joins.
Additionally, if you use the implicit join syntax, it is easy to end up with an accidental cross join if you forget to link the tables in your WHERE clause.

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)