Conditional Joins with QQ::expand() and QQ::expandAsArray()
Sometimes, you find yourself in a situation when you want to issue a query for ALL items in a given table, and only some information in another table.
For example, let's say you have a list of persons, and a related list of logins. Only some of the persons have logins; some of the logins are disabled. Your task is to show the name of every person, and next to it, show their login information, but only if their login is actually enabled.
Before you found out about conditional joins, you had several options:
- Do a LEFT JOIN on the login table; write a database-specific, somewhat convoluted IF statement that might look like IF(login.is_enabled = 1, login.username, ""). But what if you want to show more than just that one column? Write an IF statement for every single output column... Ehh. Plus, not portable across databases.
- Get a list of all persons, then also get a list of all logins, then merge the two using PHP. Works with QQuery, but incurs an overhead of extra processing.
As you'd expect, there's a better way. When you use QQ::Expand, you can specify conditions on the table with which you want to join, and get only those values that you care about. QQ::Expand clauses produce a left join - so if a row of a table with which you are joining does not have a matching record, the left side of your join will still be there, and the right side will contain nulls.
Conditional joins only impact how tables are joined together, and so the conditions must apply only to the joined table.
Names of every person, their username, and open projects they are managing.
- John Doeooo: - no login -; Managed Open Projects: Blueman Industrial Site Architecture
- Kendall Public: - no login -
- Ben Robinson: Login: brobinson
- Mike Ho: Login: mho; Managed Open Projects: State College HR Systzzzz
- Alex Smith: - no login -
- Wendy Smith: - no login -
- Karen Wolfe: - no login -
- Samantha Jones: - no login -
- Linda Brady: - no login -
- Jennifer Smith: - no login -
- Brett Carlisle: - no login -
- Jacob Pratt: - no login -
- 5 8: - no login -
- 5 8: - no login -
- 5 8: - no login -
- 57417 87887: - no login -
- Joseph Biden: - no login -
- Joseph Biden: - no login -
- Joseph Biden: - no login -
- sdbv asdgvb: - no login -
- sdbv asdgvb: - no login -
- John Doe: - no login -
- Johnww Doe: - no login -
- ttttttt yyyyyy: - no login -
- ttttttt yyyyyy: - no login -
- ttttttt yyyyyy: - no login -
- ttttttt yyyyyy: - no login -
- ttttttt yyyyyy: - no login -
- ttttttt yyyyyy: - no login -