I think I have answered this myself, but I just want to check with you guys that my logic is correct, and maybe this will help other users having similar problems.
Here is my original code snippet:
db.select()
.from(db_users)
.innerJoin(
db_organisations_users,
db_users.id.eq(db_organisations_users.user_link)
)
.innerJoin(
db_organisations,
db_organisations.id.eq(db_organisations_users.organisation_link)
)
.where(db_organisations_users.organisation_link.eq(this.orgId))
.exec()
.then(function(rows){
console.log("usersShow rows",rows);
});
This does not produce correct results, as I receive about 20 results instead of 10, and on 10 of them,
db_organisations_users.user_link !=
db_users.id.
However, swapping the innerJoins around like this:
db.select()
.from(db_users)
.innerJoin(
db_organisations,
db_organisations.id.eq(db_organisations_users.organisation_link)
)
.innerJoin(
db_organisations_users,
db_users.id.eq(db_organisations_users.user_link)
)
.where(db_organisations_users.organisation_link.eq(this.orgId))
.exec()
.then(function(rows){
console.log("usersShow rows",rows);
});
...appears at first sight to produce the results I'm after, but I am wary that as I accrue more data, a crack will also appear. So at this point I'm thinking to myself I'm probably doing something wrong.
Then I note that in the docs under 4.1 SELECT Query Builder it states:
"All functions provided by select query, except orderBy(), can only be called once, otherwise an exception will be raised."
Ah, so I'm calling .innerJoin twice, and therefore getting unexpected (and unsupported) results. So if I try:
db.select()
.from(db_users)
.leftOuterJoin(
db_organisations_users,
db_users.id.eq(db_organisations_users.user_link)
)
.innerJoin(
db_organisations,
db_organisations.id.eq(db_organisations_users.organisation_link)
)
.where(db_organisations_users.organisation_link.eq(this.orgId))
.exec()
.then(function(rows){
console.log("usersShow rows",rows);
});
...bearing in mind that in
my db there will always be a relationship between
db_users.id and
db_organisations_users.user_link, then
.leftOuterJoin() will net the same result as
.innerJoin() would, and so (hopefully) this is how to solve this kind of problem.
Hopefully.
However, if I want to run a more complex query involving a third or fourth join, I probably can't, can I?