So if I have a Javascript array of strings, how do I append each element to a row in the Postgres text[] column? This is what I'm currently using, but it's not yielding the desired result (which is just making the text array in the column of {"1","2","3"}.
let addNumbers = 'UPDATE numTable SET column1 = array_append(columnName, ($1)) WHERE uid = ($2)'
let x = ["1","2","3"]
I'm querying to the db with
query(addNumbers, [x, uid]);
I've tried using array_append but this results in the column getting a value of
{"{\"1\",\"2\",\"3\"}"}
I'd prefer not to iterate and append each one individually because this'll obviously increase the number of database calls--any help is much appreciated!
Related
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.
I have 10 rows of data on my input step, i transform them in a for-loop and i should get more than 10 rows, but in this case i get the last transform of each iteration that the loop have for each data
I tried to use appendToFile() but the result data is not useful and pentaho read it as a unique header
On my alert() method i can see that the for loop transform the data.
var PERIODO = 2
var i
var fecha_final
//var ruta_acess ="D:\TEST.accdb"
//var contenido
////var contenido2
//var arreglo_completo
for (i=0; i<=PERIODO; i++){
fecha_final = dateAdd(FECHA_INICIO,"d",i)
Alert(i)
}
As I show in the below photo i get only 10 records and in the other photo appears the result that i want that are the results data of each iteration of the for-loop
Modified JavaScript value photo:
Expected result:
Obtained result:
For loops are not really a thing in PDI. Transformations work on sets of rows that flow through the steps, so it's best for performance and stability to use that mindset.
In your scenario each incoming row should end up as three copies, but with different calculated values based on a single new field (with values 0,1,2).
The way to do this in PDI is with a Join rows (cartesian product) step. It takes two sets of input rows and outputs a row for every combination of input rows, possibly filtered by defining a key field that has to match. So if you have 10 rows in the main input and 3 rows in the second, it will output 30 rows.
You will first need to create a data grid as the second input. Define a single integer field, name it something clear and on the second tab fill three rows with 0, 1 and 2 respectively.
Connect both inputs to the Join rows step. You don't need to configure any matching key.
The output of the Join step will be three rows for each input row, one with each of the values 0, 1, 2. Connect that output to a Calculator step and use the calculation Date A + B days to replace the logic from your javascript step.
what i mean is that in the obtained result photo the "i" variable only shows the value of "3" and i would like to have "1", "2" and "3"
to solve this i used
var row = createRowCopy(getOutputRowMeta().size())
var idx = getInputRowMeta().size()
row[idx++] = DPROCESS
this add a row for each result of the iteration.
before the tranformation result showed to me only the last value of each loop.
I have a data set that I need to pivot in order to represent in a grid on screen.
I wanted to do this in the database, but the issue is the number of columns that can be returned by the query is dynamic and fluctuates based on the search criteria.
The dataset from the query looks like this:
And I need to represent it on the screen like this:
Essentially each sample ID needs to be its own line, with the test method ID's and results on the line with it.
My plan is to do the pivot on the front end, using a JQuery library if possible.
I wanted to use this https://www.npmjs.com/package/json-to-pivot-json but i do not belive it will work because of their limitation: Only supports single column, row and value for pivoting for now.
Does anyone have any libraries to recommend, or examples a pivot being done with a large dataset like I have?
All the examples I have found are very basic doing only 3 columns.
I was unable to find any library that would do a pivot for me in JQuery.
So, I created my own pivot function in Java to build a distinct list of the data, and do the pivot in a single pass through.
public List<JSONObject> getDistinctResultsAndPivot(List<LabInquiryDetail> results){
List<JSONObject> pivotData = new ArrayList<>();
String prevSampeId = "";
for (LabInquiryDetail result : results) {
/*
* If sample IDs do not match, it is either the first record in the result set,
* or a new record we have not looked at yet.
*/
if(!Objects.equals(prevSampeId, result.getSample_id())){
JSONObject row = new JSONObject();
row.put("equipmentId", result.getEquipment_id());
row.put("lot", result.getLot());
row.put("wrkOrdId", result.getWrk_ord_i());
row.put("opcodeDesc", result.getOpcode_desc());
row.put("sampleId", result.getSample_id());
row.put("sampleStatus", result.getSample_status());
row.put("sCreatedDate", result.getS_created_date());
row.put("sModifiedDate", result.getS_modified_date());
row.put("sCollectionDate", result.getS_collection_date());
row.put(result.getTm_id(), result.getResult());
pivotData.add(row);
}
/*
* Because results are already sorted by sample ID in ascending order,
* if sample IDs match, we can get the last row in our pivot list, as it is the row we need to update
* with new test method record.
*/
else if (Objects.equals(prevSampeId, result.getSample_id())){
JSONObject row = pivotData.get(pivotData.size() - 1);
row.put(result.getTm_id(), result.getResult());
}
prevSampeId = result.getSample_id();
}
return pivotData;
}
I am trying to insert a row to the bottom of a sheet, but instead of my values I see text similar to what happens when you try to print an array in Java. I checked to see if the array is made correctly with logger and it has the values I want.
var name = e.range.getRow() + SpreadsheetApp.getActiveSpreadsheet().getName();
var array = e.range.getValues().concat(name);
Logger.log(array.toString());
masterSheet.appendRow(array);
array contains a timestamp, string1, string2, and finally the name I concatenated. Instead I get something like [Ljava.lang.Object;#7dch7145
This is because appendRow() is looking for array[] not array[][].
If you attempt to append:
var array = [[1,2,3],"some string"]
It will show up as the following as it is trying to get the entire contents of the first position of the array in a single cell. It does this by returning a string of the array object which turns out to be the native code identifier.
[Ljava.lang.Object;#32dba1e2 | some string
You can append the contents of array by appending its individual members such as
ss.appendRow(array[0])
Would append
1 | 2 | 3
It looks like a problem with your use of getValues() which returns a two-dimensional array and needs to be accessed as such.
GAS API Reference: getValues()
Return
Object[][] — a two-dimensional array of values
I believe this edit to setting your var array should do the trick, assuming your data range is for a single row (index 0 will be the first row, otherwise just change the index to the row you want):
var array = e.range.getValues()[0].concat(name);
I have a website that relies on data base queries pretty heavily when custom results are requested. Theses queries inner join about 6 different tables for certain data, the data from those tables remain static for long. I have been looking at making a javascript array and using method 1 to look the data up instead to remove some of those inner joins, not all of them, but just enough to make sure my database isn't overrun. I have an example query.
//search function
function FindData(WantedID) {
var result = Array.filter(function( obj ) {
return obj.ID== WantedID;
});
return result[0];
};
//query
SELECT ItemInfo1.SimpleDescription AS Item1Simple,
ItemInfo1.FullDescription AS Item1Description,
ItemInfo1.Name AS Item1Name,
ItemInfo1.GoldCost AS Item1GoldCost,
ItemInfo2.SimpleDescription AS Item2Simple,
ItemInfo2.FullDescription AS Item2Description,
ItemInfo2.Name AS Item2Name,
ItemInfo2.GoldCost AS Item2GoldCost,
ItemInfo3.SimpleDescription AS Item3Simple,
ItemInfo3.FullDescription AS Item3Description,
ItemInfo3.Name AS Item3Name,
ItemInfo3.GoldCost AS Item3GoldCost,
ItemInfo4.SimpleDescription AS Item4Simple,
ItemInfo4.FullDescription AS Item4Description,
ItemInfo4.Name AS Item4Name,
ItemInfo4.GoldCost AS Item4GoldCost,
ItemInfo5.SimpleDescription AS Item5Simple,
ItemInfo5.FullDescription AS Item5Description,
ItemInfo5.Name AS Item5Name,
ItemInfo5.GoldCost AS Item5GoldCost,
ItemInfo6.SimpleDescription AS Item6Simple,
ItemInfo6.FullDescription AS Item6Description,
ItemInfo6.Name AS Item6Name,
ItemInfo6.GoldCost AS Item6GoldCost,
ItemInfo7.SimpleDescription AS Item7Simple,
ItemInfo7.FullDescription AS Item7Description,
ItemInfo7.Name AS Item7Name,
ItemInfo7.GoldCost AS Item7GoldCost,
Spell11.Description AS Spell1Description,
Spell11.Name AS Spell1Name,
Spell11.SpellKey AS Spell1Key,
Spell11.Cooldown AS Spell1Cooldown,
Spell12.Description AS Spell2Description,
Spell12.Name AS Spell2Name,
Spell12.SpellKey AS Spell2Key,
Spell12.Cooldown AS Spell2Cooldown,
masteries.MasteryID,
masteries.MasteryName,
masteries.MasteryDescription,
matchhistory.*,
championdb.ChampName,
player.Alias,
player.RoleSlug,
player.Region,
player.AltRegion,
player.playerid,
player.SummonerIcon,
teams.Name,
teams.ID AS TeamID,
player.League,
player.Division,
player.Points,
player.isFreshBlood,
player.isHotStreak,
player.isVeteran,
player.Wins,
player.Losses,
player.FirstChamp,
player.SecondChamp,
player.ThirdChamp
FROM matchhistory
INNER JOIN player ON matchhistory.SummonerID = player.playerid
INNER JOIN teams ON player.Team = teams.ID
INNER JOIN summonerspells AS Spell11
ON matchhistory.Spell1 = Spell11.SpellID
INNER JOIN summonerspells AS Spell12
ON matchhistory.Spell2 = Spell12.SpellID
INNER JOIN items AS ItemInfo1 ON matchhistory.Item0 = ItemInfo1.ItemID
INNER JOIN items AS ItemInfo2 ON matchhistory.Item1 = ItemInfo2.ItemID
INNER JOIN items AS ItemInfo3 ON matchhistory.Item2 = ItemInfo3.ItemID
INNER JOIN items AS ItemInfo4 ON matchhistory.Item3 = ItemInfo4.ItemID
INNER JOIN items AS ItemInfo5 ON matchhistory.Item4 = ItemInfo5.ItemID
INNER JOIN items AS ItemInfo6 ON matchhistory.Item5 = ItemInfo6.ItemID
INNER JOIN items AS ItemInfo7 ON matchhistory.Item6 = ItemInfo7.ItemID
INNER JOIN masteries ON matchhistory.KeystoneID = masteries.MasteryID
INNER JOIN championdb ON matchhistory.ChampID = championdb.ChampID
ORDER BY matchhistory.TimeStamp DESC LIMIT 10;
I'm looking to reduce the item inner joins as their are 6 items in the main table, and i need to inner join each time to get the specific data for each item. In Total there is 200 items. I am using mysql, I am also looking at replacing inner join with WHERE ID IN to increase query speed. I can cache the array results also to make it faster, the array data is made with a once off query. My database server is separate from my webapp server
You are doing several mistakes
1) you fetch whole DB table join into a javascript and than you try to find specific match.
Thats very bad idea performance wise, especialy if you expect your tables to grow. Where clausule is there for a reason.
2) your DB tables are not properly indexed it seems.
based on your explain mysql is doing full table scan on player table and than scaning match history table adding multiple rows from other tables, creating temorary table for sorting (might be eaven Disk Table), sorting it (wihout index) and than fetching your 10 lines of data.
What you need is to add index on matchtable on ID colum you should be matching and than add timestamp colum to enable sorting by index. this have to be combined with where clausule containing specific ID your are searching for.
But .... based on sections of code you provided I am not sure that your problem is with database, Because eaven small instance of mysql have to handle this in few ms.