Using data from 2 queries in order to make a graph - javascript

I have three tables in MySQL.
Staff with fields id, name, surname, telephone, adress, id_work.
Work with fields id, name.
Absence with fields id, name, id_staff.
Also,I have the following queries:
Query 1
SELECT COUNT(*)
FROM staff s
INNER JOIN work w ON s.id_work = w.id
LEFT JOIN absence a ON s.id = a.id_staff
WHERE w.name='sales manager'
AND a.name = 'disease'
AND a.id_staff IS NULL;
Query 2
SELECT COUNT(*)
FROM staff s, work w, absence a
WHERE s.id=a.id_staff
AND s.id_work=w.id
AND w.name='sales manager'
AND a.name='disease'.
As it seems, the first query is inverse of second query. I want to make a graph which seems the % of the staff who is active/inactive. I decide to use google graphs and especially 3D pie chart:
https://developers.google.com/chart/interactive/docs/gallery/piechart#making-a-3d-pie-chart
I try to connect mysql with javascript via Ajax but dont work
Do you nhave any other idea in order to make this graph using data from those queries

Related

How to conditionally insert into mariadb based on if the entry already exists

I have the following:
Table with ID, title, userid
At the moment I have logic that when a certain media is viewed it is entered into the database in order to store view history.
Now, I am trying to prevent duplicate entries from being inserted. This is the code that I have tried and it is still duplicating entries.
dataAccessor.viewers = {
add: ({ courseId, viewerOid }) => {
const query =
"IF NOT EXISTS (SELECT * FROM course_video_viewers WHERE course_id = ? AND WHERE azure_oid = ?) INSERT INTO course_video_viewers (course_id, azure_oid) VALUES (?, ?)";
const inputs = [courseId, viewerOid];
return sendQueryAndReturnResultsAsPromise(query, inputs);
}
};
Looks like you should have a unique index on course_id,azure_oid That would prevent duplicates from being inserted. Then you can run insert ignore into course_video_viewers... and it will internally drop the record if it exists and reinsert it.
The best thing to do is to add a unique constraint in the table for the combination of the columns course_id and azure_oid:
ALTER TABLE course_video_viewers
ADD CONSTRAINT un_con_video_view
UNIQUE (course_id, azure_oid);
If you can't alter the table's definition you can use a INSERT ... SELECT statement:
INSERT INTO course_video_viewers (course_id, azure_oid)
SELECT ?, ?
FROM dual
WHERE NOT EXISTS (SELECT * FROM course_video_viewers WHERE course_id = ? AND WHERE azure_oid = ?)
You may omit FROM dual if your version of MySql is 5.7+.

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.js - subselect in join clause

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

how to update two rows in a single table with one command in my sql

I have a table
accountdetails
with fields
customerid,balance,account id
Now Im trying to update this through my node app where when I transfer amount, in one record the value should be debited and in another it should be credited
var data = {customerid,transferamount,accountid};
con.query('update accountdetails set balance = balance-? WHERE customerid = ? ,
[data.transferamount,data.customerid]')
con.query('update accountdetails set balance = balance+? WHERE accountid = ?,
[data.transferamount,data.accountid]')
So currently I have two commands to do this how can we limit this to one command since both are basically updating single table.
Any idea
Agree with #kawadhiya21, maybe better don't do it... you have to benchmark both cases to figure out performance, but in general, it is possible:
sql = 'update accountdetails';
sql += 'set balance = if(customerid = ?, balance - ?, if(accountid = ?, balance + ?, balance) ) ';
sql += 'where customerid = ? or accountid = ?';
con.query(sql, [
data.customerid,
data.transferamount,
data.accountid,
data.transferamount,
data.customerid,
data.accountid
]);
One of the best practices is utilising mysql's Triggers. These are programmable database objects that do the job.
What you basically describe is an AFTER UPDATE trigger. For Example:
CREATE TRIGGER doTheJob AFTER UPDATE ON accountdetails
FOR EACH ROW
BEGIN
UPDATE accountdetails
SET balance = +? WHERE accountid = ?
END;
DELIMITER ;
More info specifically on AFTER UPDATE triggers here
More info on triggers here
Another way is to use stored procedures to accomplish this:
https://dev.mysql.com/doc/connector-net/en/connector-net-tutorials-stored-procedures.html
With a stored procedure you can add 3 parameters (customerid, transferamount, accountid) and hide all the internal details of the SQL calls (for instance the solution from Vladimir Kovpak)
Good day,
Yes these two commands must remain to update your data, since you have different conditions on your commands.
Your first command condition is WHERE customerid, while the other command condition is WHERE accountid, so it is not possible to combine these into one single command.

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