Sequelize.js - subselect in join clause - javascript

I have two tables - customer and order with one-to-many relationship. I want to retrieve in a single query all customer data and total value of his orders.
In raw SQL that would be something like this:
select customer.*, o.total from customer
inner join (select sum(value) as total, customer_id from
order group by customer_id) as o
on customer.id=i.customer_id
My question is - how to express this query in Sequelize without writing SQL? Is this even possible?

Try this:
const query = `
SELECT
table_a.table_a_id AS "table_a.table_a_id",
table_b.table_b_id AS "table_b.table_b_id"
FROM
table_a
LEFT JOIN
(SELECT * FROM table_b) AS table_b
ON
table_a.table_b_id = table_b.table_b_id
`;
const options = {
model: models.table_a,
mapToModel: true,
nest: true,
raw: true,
type: sequelize.QueryTypes.SELECT
};
let tableAs = await db.sequelize.query(query, options);
Please note that you need the alias in the select statements. Seems like Sequelize.js differentiates the tables by the dot in the name.
caution: this doesn't work if table_a and table_b has "one to many" relationship because table_bs must be array. This seems like just overwrite table_b without making it array.

Hi xersee first you want to create two tables customer and order in sequalize.js format
Then after summation of value column and customer_id column from table order put it into one table
Then after that just join the new table with customer table in ORM Style
Please refer below link it may be help for you.
How to make join querys using sequelize in nodejs

Related

How can I INSERT new values and values from an already existing table?

I'm currently learning MySQL and have learned the INSERTO INTO statement and the INSERT INTO SELECT statement.
The INSERT INTO statement works like this:
INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);
While the INSERT INTO SELECT works like this:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;
What I'm trying to do is add new values while also adding values that I already have stored in another table.
con.query("INSERT INTO vehicles (vehicleType, vehicleModel, vehicleOwner, vehicleSpawnX, vehicleSpawnY, vehicleSpawnZ)")
From the query above, I already have the vehicleOwner value stored in another table, while the other ones I've just gotten.
How can I do this? Add a VALUES statement before SELECT?
I'm using SQL Workbench 8.0 and JavaScript. Also, all the values are NOT NULL, so I can't make two different queries, unless on the first one I add temporary values that I'll update on the second one.
What I want to replace:
vehicleType -> "players"
vehicleModel -> vehicleCreate.model
vehicleOwner -> playerID FROM players table
vehicleSpawnX -> pos.x
vehicleSpawnY -> pos.y
vehicleSpawnZ -> pos.z
Thanks!
It's not possible... But you can select data and store that on variables, then you will store it in another table
You would construct a query. Your data model is a bit hard to follow since you give no examples of the data or of what you really want to do.
So let me give a simpler example. Say, you have a table with two columns for two players and you want to put the ids into a table -- but using their names. The query would look like:
insert into pairs (playerId1, playerId2)
select p1.playerId, p2.playerId
from players p1 join
players p2
on p1.name = ? and p2.name = ?;
The ? are for parameter placeholders. I assume you know to aways use parameters when passing values into a query.

Sequelize performs extra SELECT query before updating associations

Sequelize seems to introduce unnecessary queries when adding new associated record to a source record.
For example, consider a regular many-to-many association with a Users model and a Groups model, where a user belongsToMany groups, and each group belongsToMany users.
If I create a new user record, then add two existing groups to that user, Sequelize executes what seems to be an extra unnecessary
SELECT` query:
const record = await Users.create({id: 1, name: 'John'})
await record.addGroups([2,3]);
The above call to record.addGroups([2,3]) leads to these two MySQL queries:
SELECT group_id
, user_id
,
FROM user_groups
WHERE user_groups.user_id = 1
AND user_groups.group_id IN ('2', '3');
INSERT INTO user_groups (group_id,user_id) VALUES
('2','1'),('3','1');
1) What is the cause of the first SELECT query above?
2) Are there any benefits including that query?
3) Are there any ways to disable this extra SELECT query?

How to use LAST_INSERT_ID() to INSERT multiple records with the same value

So most questions about LAST_INSERT_ID() with multiple INSERT records involve getting multiple IDs back after the insert, my question is backwards from that.
I have table foo, with a many-to-many relationship with bar, and a junction table, foo__bar. I want to INSERT a single foo record, but also an unknown quantity of bar associations, so I need the LAST_INSERT_ID() after the first INSERT statement, but multiple times:
const db = require('mysql');
...
//connection and pooling set up
let sql = `INSERT INTO foo VALUES(null, ?, ?);
INSERT INTO foo__bar((LAST_INSERT_ID(), ?), (LAST_INSERT_ID(), ?)//etc
`;
let barIds = [1,4];
let params = [name, description, barIds[0], barIds[1]];
let result = await db.query(sql, params);
This works fine if the bar table is already populated and the bar ids are valid, and I only ever do two associations per INSERT:
--table foo__bar
+------+------+
|foo_id|bar_id|
|------|------|
| 1| 1|
|------|------|
| 1| 4|
+------+------+
But what if I have multiple values/associations? Using the 'mysql' npm package, normally I could just do this and an array will be converted into ((val1, val2),(val1, val2),(val1,val1)) etc. However, for my junction table, I need val1 to be the same every time, specifically LAST_INSERT_ID(). Is this possible without having to make two async calls to the database?
Thanks

Sequalize limit by unique values in column

I have the following database structure:
id (int) | user_id (int) | product_id (int) | data (jsonb)
A combination of the id, user_id and product_id make the primary key. So there can be multiple rows with the same product_id and user_id.
The data column has some JSON containing the following
{ "item": boolean }
The query I need is to select all rows where user_id = x and data-->item = true. This part I can do, but I need to apply a limit. The limit should not restrict the number of rows that are returned, but instead restrict the number of DISTINCT product_ids that are returned. So if I apply a limit of 10 I could have 50 rows returned if each of the unique products have 5 rows belonging to the user_id and and item true.
This is what I have so far but it makes no attempt at this limit. I believe I may need a subquery or GROUPBY but I'm not sure how to achieve this in Sequalize.
return this.myModel.findAll({
where: {
user_id: userId,
'data.item': true,
},
});
Any guidance will be much appreciated! Thanks
A query to do this involves JOINing a subquery:
SELECT m.*
FROM my_model m
JOIN (
SELECT DISTINCT product_id FROM model LIMIT 10
) n ON n.product_id = m.product_id
WHERE m.user_id = $1 AND (data->>'item')::boolean IS TRUE;
To my knowledge, Sequelize cannot represent this query structure, although inlining the subquery as a literal may be possible. But it looks like you'll be running at least some raw SQL one way or the other.

is - select * from empty table possible?

On my website I am trying to select 2 tables - tableB of which might be empty, so its not returning any results at all when tableB is empty. I hope I am explaining this properly. Any suggestions?
curatio.webdb.getAllTodoItems = function(renderFunc) {
var db = curatio.webdb.db;
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM tableA, tableB", [], renderFunc,
curatio.webdb.onError);
});
}
basically TableA has e.g. Name and Surname columns and TableB has e.g. Address details. But sometimes there is no address, and then I cannot get anything to display.
I need to basically ignore tableB if it's empty.
If tableA and tableB have the same schema, you can do something like this:
SELECT * FROM tableA
UNION
SELECT * FROM tableB
However, if they don't have the same schema, you will have to do something smarter to get the union to work.
Although your query doesn't hint at this, I still think you are probably looking for a LEFT JOIN, because I'm assuming you want to link data from two tables by a common value in a column from table B (known as the foreign key).
This query selects values of the first table, even when there's no matching data in the join table:
SELECT *
FROM `tableA` `a`
LEFT JOIN `tableB` `b`
ON `b`.`someReferenceColumnToTableA` = `a`.`theReferredColumn`
Again, this assumes you meant to join two tables by some common value, for instance:
person (table A):
- id
- name
phonenumber (table B):
- id
- person_id // this is the foreign key to table A that "links" the data
- phonenumber
If you were to use a regular JOIN (also known as INNER JOIN) then only rows are returned for when both tables have matching data.
What your original query did, however, was (implicitly) CROSS JOIN all data from both tables. Given your question edit, I hardly think this is what you were actually after.
What you are performing there is called a Cross-Product of those two tables. A cross-product is essentially every row of tableA with every row of tableB. Since tableB has no rows, the cross-product has no rows. If you want all rows of both tables, use 2 queries. I would recommend reading a basic SQL tutorial.
curatio.webdb.getAllTodoItems = function(renderFunc) {
var db = curatio.webdb.db;
db.transaction(function(tx) {
tx.executeSql("SELECT * FROM tableA UNION ALL SELECT * FROM tableB", [], renderFunc,
curatio.webdb.onError);
});
}
It will best to explicitly use the column names in both select rather then using the *.

Categories