Question: It is possible to join the result of a complex query to another table.
See original GitHub issueI’ve been playing around with this, trying to get it to work in Knex:
knex.raw '''
SELECT
id,
name,
fluid_account_id,
survey_fid,
coalesce(assigned_client_count, 0) as assigned_client_count
FROM (
SELECT survey_id, count(*) as assigned_client_count
FROM client_surveys
GROUP BY survey_id
) t_counts
RIGHT JOIN
fluid_surveys
ON
t_counts.survey_id = fluid_surveys.id
'''
Is it possible to express this without using raw? The main advantage to not using raw is that I can pass an Javascript object straight into the where
function, which makes for some really clean code.
If it’s not possible to do this complex a query with knex, is it possible for me to augment this raw query with where
?
This is what I hoped would work:
sub = knex 'client_surveys'
.select [
'survey_id'
knex.raw 'count(*) as assigned_client_count'
]
.from 'client_surveys'
.groupBy 'survey_id'
knex 'fluid_surveys'
.select [
'id'
'name'
'fluid_account_id'
'survey_fid'
knex.raw 'coalesce(assigned_client_count, 0) as assigned_client_count'
]
.join sub, 't_count.survey_id', '=', 'fluid_surveys.id'
.then (result) ->
console.log "result", result
Issue Analytics
- State:
- Created 9 years ago
- Comments:8 (8 by maintainers)
Top Results From Across the Web
Learn SQL: Join multiple tables - SQLShack
We've used INNER JOIN 2 times in order to join 3 tables. This will result in returning only rows having pairs in another...
Read more >The Top 10 SQL JOIN Interview Questions and How to Answer ...
Typically, the JOIN condition is an equality between columns from the different tables, but other JOIN conditions are also possible.
Read more >Complex SQL query to join two tables - oracle - Stack Overflow
Problem : Given two tables: TableA, TableB, where TableA has a one-to-many relationship with TableB, I want to retrieve all records in TableB...
Read more >Question: It is possible to join the result of a complex query to ...
I've been playing around with this, trying to get it to work in Knex: knex.raw ''' SELECT id, name, fluid_account_id, survey_fid, ...
Read more >SQL joins and how to use them - Launch School
In other words, the join table of a cross join contains every possible combination of rows from the tables that have been joined....
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
This:
or this:
should get what you’re after.
That was the problem.
Thanks again!