I have a question about the snippet below. I'm wondering, if the first query doesn't bring any results, would I still get the results for the second query?
select *
from
(
-- first query
) as query1
left join
(
-- second query
) as query2
on query1.id=query2.id
left join
(
-- third query
) as query3
on query1.id=query3.id;
Update:
what I need is a full join, however, MySQL does not开发者_StackOverflow support it, what would be a good way to emulate this?
The answer is no.
A left join will pull all results from the left, and only those results on the right that match. A right join does the reverse. A full outer join will pull all results from either and join just those that can be joined.
Note that with current databases it is wise to avoid full outer joins because they are much less efficient than other joins. I have personally managed to beat full outer joins in Oracle and PostgreSQL by orders of magnitude with tricks like this, which can also be used to emulate full outer joins in databases that don't have them:
SELECT some_id
, MAX(foo) AS foo
, MAX(bar) AS bar
, MAX(baz) AS baz
, MAX(blat) AS blat
FROM (
SELECT A.some_id
, A.foo
, A.bar
, NULL as baz
, NULL as blat
FROM A
UNION ALL
SELECT B.some_id
, NULL as foo
, NULL as bar
, B.baz
, B.blat
FROM B
) AS subquery
GROUP BY some_id;
There is a possibility that this query will not work as is because the database won't figure out the types of the null columns. There are workarounds for that. The simplest is to create a temp table with explicit column types, emulate the UNION ALL with 2 insert queries, then query off of the temp table.
(See http://bentilly.blogspot.com/2011/02/sql-formatting-style.html for an explanation of my formatting style.)
No, you would need to do a right join instead.
No, because results from the second query appends to the results from the first query.
No because you have left join. Records from second are added to first. If there are no first no record from second can be added. Revers is possible via right join.
精彩评论