I want to add a sub-query as a column using knex.
Example SQL query:
select
name,
(select count(*) from employee where employee.dept_id = 1) as employees_count
from
department
where
department.id = 1
I tried
knex('department').select('name', knex('employee').count().where({dept_id: 1}))
.where({id: 1})
but it didn't work
To help yourself localize the issue, you can add .debug() to your querybuilder. That allows you to see the actual rendered query. This will not solve your issue, but will give you insight into how Knex sees your query.
To solve your issue, try some combination of select and raw. Like:
let emp = knex('employee').count().where({ dept_id: 1 })
knex('department')
.select('name')
.select(knex.raw('? as employee_count', emp))
//.debug()
use .debug() to clear out minor issues.
const Knex = require('knex');
const knex = Knex({
client: 'pg',
});
knex('department').select(
'name',
knex('employee').count().where({dept_id: 1})
.as('employees_count')
).where({id: 1}).toSQL().sql;
// "select \"name\", (select count(*) from \"employee\" where… \"employees_count\" from \"department\" where \"id\" = ?"
https://runkit.com/embed/q22w8v6z5n61
Related
Below is my code base with the query
export const getQuery = (idList) => {
return `SELECT * from glacier_restore_progress where id in ${idList}`;
}
const query = getQuery('(1,2)');
dbResponse = await pool.query(query)
...
it works fine. But the Sql Injection issue is popping from my sonar server.
So i tried below code change and it didn't work,
...
dbResponse = await pool.query('SELECT * from glacier_restore_progress where id in $1', ['(1,2)']);
What am i missing here?
The best solution uses the ANY function with Postgres array coercion. This lets you match a column with an arbitrary array of values as if you had written out col IN (v1, v2, v3). This is the approach in pero's answer.
SELECT * FROM glacier_restore_progress WHERE id = ANY($1::int[])
dbResponse = await pool.query('SELECT * FROM glacier_restore_progress WHERE id = ANY($1::int[])', [[1,2, ...]]);
I am new here recently joined and New in Type ORM My code that I am trying
FIRST QUERY: I would like to use this approach but not sure how I can group by with count on the column and then order by desc on that column
const result = await this.jobViewsRepository.find({
relations: ["jobs"],
loadEagerRelations: true,
order: { id: "DESC" },
skip: offset,
take: limit,
}
);
I am trying if I can use this in my above query
SECOND QUERY: IT'S WORKING FOR ME PERFECTLY THE RESULT I AM LOOKING
const res = await this.jobViewsRepository.createQueryBuilder('jobViews')
.addSelect("COUNT(jobViews.user_id) AS jobViews_total_count" )
.leftJoinAndSelect(Jobs, "jobs", "jobs.id = jobViews.job_id")
.where("jobs.user_id != :id", { id: user_id })
.groupBy("jobViews.job_id")**
.orderBy('jobViews_total_count', 'DESC')**
.limit(limit)
.offset(offset)
.getRawMany();
Please if any can help me out in this will be really appreciated
Thanks
At least in the current version there is no way to do this feature (neither in the documentation nor in the web)
I believe you can use .query to write your own query
Now is the only one way is to use queryBuilder And .groupBy("user.id") with .addGroupBy("user.id")
https://orkhan.gitbook.io/typeorm/docs/select-query-builder#adding-group-by-expression
Or write raw query:
import { getManager } from 'typeorm';
const entityManager = getManager();
const someQuery = await entityManager.query(`
SELECT
fw."X",
fw."Y",
ew.*
FROM "table1" as fw
JOIN "table2" as ew
ON fw."X" = $1 AND ew.id = fw."Y";
`, [param1]);
you use findAndCount to count the result size
result = await this.jobViewsRepository.findAndCount({ ... })
the result = [data,count]
This is the query I'm firing off:
const updatedUser = await queryRunner.manager
.getRepository(UserEntity)
.createQueryBuilder('user')
.leftJoinAndSelect('user.categories', 'cats')
.where('id = :userId', { userId })
.getOne();
And here is the query that is generated by typeorm:
SELECT "user"."id" AS "user_id",
"user"."first_name" AS "user_first_name",
"user"."last_name" AS "user_last_name",
"user"."phone" AS "user_phone",
"user"."password" AS "user_password",
"user"."password_hint" AS "user_password_hint",
"user"."recovery_email" AS "user_recovery_email",
"user"."created" AS "user_created",
"user"."username" AS "user_username",
"user"."profile_pic" AS "user_profile_pic",
"user"."is2fa" AS "user_is2FA",
"user"."refresh_token" AS "user_refresh_token",
"user"."profile_email" AS "user_profile_email",
"user"."subscriptionid" AS "user_subscriptionId",
"cats"."id" AS "cats_id",
"cats"."template_id" AS "cats_template_id",
"cats"."name" AS "cats_name",
"cats"."entry_count" AS "cats_entry_count",
"cats"."is_base_template" AS "cats_is_base_template",
"cats"."can_rename" AS "cats_can_rename",
"cats"."can_delete" AS "cats_can_delete",
"cats"."userid" AS "cats_userId",
"cats"."position" AS "cats_position",
"cats"."icon_path" AS "cats_icon_path",
"cats"."init_name" AS "cats_init_name",
"cats"."isfortasks" AS "cats_isForTasks",
"cats"."is_locked_by" AS "cats_is_locked_by",
"cats"."is_locked" AS "cats_is_locked",
"cats"."password" AS "cats_password",
"cats"."state" AS "cats_state",
"cats"."password_hint" AS "cats_password_hint",
"cats"."parentcategoryid" AS "cats_parentCategoryId"
FROM "user" "user"
LEFT JOIN "category" "cats"
ON "cats"."userid" = "user"."id"
WHERE id = $1
If I remove the leftJoinAndSelect it doesn't yield that error but I need this join.
What is wrong with the query?
META:
The DBMS I'm using is PostgreSQL v. 12.3.
Well, as you can see there is a user.id and a cats.id available - you even select both. But in the WHERE clause you don't say which id you mean. Change 'id = :userId' to 'user.id = :userId' and it should work.
Am new in Node Js, In my Node Js project am using sequelize ORM with MySql database.
This is my query i want to write select query by month.
This is my query SELECT * FROM cubbersclosure WHERE MONTH(fromDate) = '04'
Here fromDate field type is date
This my code:
var fromDate = '2019-04-01'
var fromDateMonth = new Date(fromDate);
var fromMonth = (fromDateMonth.getMonth()+ 1) < 10 ? '0' + (fromDateMonth.getMonth()+1) : (fromDateMonth.getMonth()+1);
CubbersClosure.findAll({
where:{
// select query with Month (04)... //fromMonth
}
}).then(closureData=>{
res.send(closureData);
}).catch(error=>{
res.status(403).send({status: 'error', resCode:200, msg:'Internal Server Error...!', data:error});
});
Here fromMonth get only month from date, so i want to write code select query by month.
I'm not sure but what about try this?
where: {
sequelize.where(sequelize.fn("month", sequelize.col("fromDate")), fromMonth)
}
for those of you looking for postgres, this is a somewhat hacky way to make this work (make sure to unit test this):
const results = await models.users.findAll({
where: this.app.sequelize.fn('EXTRACT(MONTH from "createdAt") =', 3)
});
you can also take this a step further and query multiple attributes like so:
const results = await models.table.findAll({
where: {
[Op.and] : [
this.app.sequelize.fn('EXTRACT(MONTH from "createdAt") =', 3),
this.app.sequelize.fn('EXTRACT(day from "createdAt") =', 3),
]
}
});
I want to fetch more than 100 records from azure-cosmos DB using select query.
I am writing a stored procedure and using a select query to fetch the record.
SELECT * FROM activities a
I am getting only 100 records though there are more than 500 records.
I am able to get all records usings the setting configuration provided by Azure.
I want to perform the same operation using query or stored procedure. How can I do that ??
Please suggest changes that need to accomplish.
I am writing a stored procedure and using a select query to fetch the record.
SELECT * FROM activities a
I am getting only 100 records though there are more than 500 records.
The default value of FeedOptions pageSize property for queryDocuments is 100, which might be the cause of the issue. Please try to set the value to -1. The following stored procedure works fine on my side, please refer to it.
function getall(){
var context = getContext();
var response = context.getResponse();
var collection = context.getCollection();
var collectionLink = collection.getSelfLink();
var filterQuery = 'SELECT * FROM c';
collection.queryDocuments(collectionLink, filterQuery, {pageSize:-1 },
function(err, documents) {
response.setBody(response.getBody() + JSON.stringify(documents));
}
);
}
If anyone hits this page, the answers above are obsolete.
#azure/cosmos now has some options like below for those who are interested:
const usersQuery = {
query: "SELECT * FROM c where c.userId = 'someid'" +
" order by c.userId asc, c.timestamp asc"
};
const { resources: users } = await container.items
.query(usersQuery, { maxDegreeOfParallelism: 5,maxItemCount: 10000 }).fetchNext()
For reference, see here.