I am trying to make a left join to the same table in the same query but the result is not okey, I resolved the problem with a subquery this is the wrong query:
SELECT * FROM TableA ta
LEFT JOIN TableA Lta ON ta.key = Lta.key
AND ta.state IN('C')
AND Lta.state IN ('A','E')
WHERE Lta.key is null
This is the way how I resolved
SELECT * FROM (
SELECT * FROM TableA ta
WHERE ta.state IN('C')
) AS T LEFT JOIN TableA Lta ON T.key = Lta.key
AND Lta.state in ('A','E')
WHERE Lta.key IS NULL
I am a little confused with those queries if you can give me some information related to this topic I will be so grateful to you
Thank you
The self-join is a special kind of joins that allow you to join a table to itself using either LEFT JOIN or INNER JOIN clause. You use self-join to create a result set that joins the rows with the other rows within the same table.
To form a self-join, you specify the same table twice with different table aliases and provide the join predicate after the ON keyword. In this syntax, the table_name is joined to itself using the INNER JOIN clause.
While most JOINs link two or more tables with each other to present their data together, a self join links a table to itself. This is usually done by joining a table to itself just once within a SQL query, but it is possible to do so multiple times within the same query.
Again, if we perform a left outer join where date = date, each row from Table 5 will join on to every matching row from Table 4. However, in this case, the join will result in 4 rows of duplicate dates in the joined DataSet (see Table 6).
You were very close in your first query. Move the "ta.state" to the where clause. The join is how the two tables relate but secondary criteria on JUST the "lta" alias.
SELECT
*
FROM
TableA ta
LEFT JOIN TableA Lta
ON ta.key = Lta.key
AND Lta.state IN ('A','E')
WHERE
ta.state IN('C')
AND Lta.key is null
So your primary criteria is WHERE the ta.state is "C", but then only if there is NOT a match for the "A" and "E" instances in the second (left-join) alias of lta
For "not-existance" checking case I strongly recommend you to use not exists
subquery:
SELECT * FROM TableA ta
WHERE not exists
(
SELECT 1 FROM TableA Lta
WHERE ta.key = Lta.key
AND ta.state IN('C')
AND Lta.state IN ('A','E')
)
this is the most performance-friendly approach.
Not sure but it's likely that you should move ta.state = 'C'
to the outer where
clause.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With