Left join question
Left join question
Hi everyone,
I am trying to implement a one-to-many left join with an 'AND' (instead of where) clause.
My primary table is customers (PK = customer_id)
The joined table is files (PK = file_id)
The query I need to display is
SELECT * FROM customers
LEFT JOIN files on customers.customer_id = files.entity_id AND entity_type='customer'.
If AND is swapped with WHERE, only customers that have associated files are returned. I need to have all customers returned.
Is this query type possible with the Mjoin class?
I hope the above makes sense, thank you
This question has an accepted answers - jump to answer
Answers
With an Mjoin, currently no, that is not possible at this time. You can use a left join with an arbitarily complex expression, but Mjoin is a simple matching condition.
Allan
Thank you for your reply Allan,
I tried the left join with a complex however it returns as many customer entries (rows) as the files are.
I need it to return just one row per customer, regardless of how many files there are attached.
You are suggesting that the mjoin won't work at this time.
Is there a way of achieving this one-to-many relationship with a complex left join?
Your example here is almost exactly what I need, minus the 'AND' condition.
Any ideas apart from redesigning the database?
Thanks, Nico
Looking at your query again, what table is
entity_type
on? If it is thefiles
table, you could apply that as awhere
condition to theMjoin
, since it isn't actually part of the join condition. I.e. I think your query above could be rewritten as:Is that fair to say?
Allan
Hi Allan,
I have changed the code to make use of the mjoin and indeed it returns one row per customer, thanks.
The issue now is that I get an error when I use the where statement, here is the code:
and the error is:
Any thoughts?
Yup. Some even relate to this ;-)
the arguments are wrong. They should be:
The header for the function is:
Allan
Thanks a lot Allan!