mysql query works in phpmyadmin but not in node.js - mysql

I have a query like this...
SELECT *
FROM `000027`,`000028`
WHERE `000027`.id=(SELECT max(`000027`.id) FROM `000027`)
AND `000028`.id=(SELECT max(`000028`.id) FROM `000028`)
which returns something like this in phpmyadmin...
id time value id time value
However, in react.js it is only returning one of these like this...
id time value
2 questions, Why is it doing this? and, how can I get it to return both instead of one?
my node.js code...
const sqlSelect = "SELECT * FROM `000027`,`000028` WHERE `000027`.id=(SELECT max(`000027`.id) FROM `000027`) AND `000028`.id=(SELECT max(`000028`.id) FROM `000028`)"
dbPlant.query(sqlSelect, (err, result) => {
console.log(result)
res.send(result)
res.end()
})
and it sends this back with only one rowdatapacket when it should be two, or two of each of those values...
[
RowDataPacket {
id: 652,
time: 2021-01-24T17:28:01.000Z,
value: '262'
}
]

Your two tables have some column names in common. This is okay to have repeated column names in a result set in the mysql client, but some programming interfaces map a rows of a result set into a hash array, where the column names are the keys. So if you have duplicate column names, one naturally overwrites the other.
The remedy is to define column aliases for one or the other of each duplicate, so they are mapped into distinct keys in the result set.
You must do this one column at a time. Sorry, you can't use SELECT * anymore (you shouldn't use SELECT * anyway). There is no "automatic alias all columns" option.
SELECT
`000027`.id AS id27,
`000027`.time AS time27,
`000027`.value AS value27,
`000028`.id AS id28,
`000028`.time AS time28,
`000028`.value AS value28
FROM `000027`,`000028`
WHERE `000027`.id=(SELECT max(`000027`.id) FROM `000027`)
AND `000028`.id=(SELECT max(`000028`.id) FROM `000028`)

Related

How to access query result with the selection as object name

I have made a query on a data and it returns a result:
[ RowDataPacket { 'COUNT(t.id)': 2 } ]
How can I access it like the count number?
I have tried result.COUNT(t.id) but it isn't worked.
The way the object is named, you need to access it like so:
result[0]["COUNT(t.id)"]
I would rather name the columns explicitly by using aliases in the query:
select count(t.id) as count_of_id
from ...

How to search a json encoded array column in a table with respect to an array and return the matching result?

I have a mysql table that contains a column user_ids - this column holds json encoded array of user ids.
Just like this -
row0 - "[145,146]",
row1 - "[145]",
row2 - "[141,143,145]",
row3 - "[142,146,147]"
Now I want to search inside the user_ids column for each row with respect to another array of user_ids supplied as an argument. I want all the matched rows to be returned as a result of this query.
I have tried to implement it like this in Laravel but it didn't return any rows-
$booked_courses = $booked_courses->where(function ($query) use ($user_ids) {
$query->orWhere('user_ids', 'LIKE', '%'.json_encode($user_ids).'%');
});
Also I thought looping over the decoded array might yield the result but didn't succeed, tried to do the following -
$booked_courses = $booked_courses->where(function ($query) use ($user_ids) {
foreach(json_decode($query->user_ids) as $u_id) {
$query->whereIn($u_id, $user_ids);
}
});
Any help in raw sql as well, will be very helpful for me. Or please suggests me some ways to fetch the desired result. Thank you so much for your time.

Mysql for NodeJS not expanding array in queries

I'm using NodeJS and the mysql package from npm. I'm having trouble selecting specific rows from the database by ID. I'm using a simple WHERE id IN (...) query, and passing in the ids as an array of numbers.
According to the documentation,
Arrays are turned into list, e.g. ['a', 'b'] turns into 'a', 'b'
So I've written this code to debug the SQL it generates:
console.log(ids);
console.log(this.connection.format(
"SELECT `invitations`.* FROM `invitations` WHERE `invitations`.`id` IN (?)",
ids
));
I expect to see a list of ids first, then the SQL statement where those ids are in the IN section of the query.
However, only the first id is present in the query:
console.log tests/fakers/InvitationFaker.ts:70
[ 207, 208 ]
console.log tests/fakers/InvitationFaker.ts:71
SELECT `invitations`.* FROM `invitations` WHERE `invitations`.`id` IN (207)
Why doesn't the query look like this:
... WHERE `invitations`.`id` IN (207, 208)
?
try to convert the ids to string with "," between the ids
this.connection.format(
"SELECT `invitations`.* FROM `invitations` WHERE `invitations`.`id` IN (?)",
ids.join(",")
));
I'm an idiot :) I forgot that the second argument can be either a single value or an array, but when it's an array, the first value fills the first ? and so on. To expand an array, I need to do this:
" ... WHERE `id` IN ?", [ids]
(note the double array, since ids is already an array). For example:
" ... WHERE `id` IN ?", [[1, 2, 3, 4]]

MariaDB COLUMN_JSON query returns binary

I've been trying to use dynamic columns with an instance of MariaDB v10.1.12.
First, I send the following query:
INSERT INTO savedDisplays (user, name, body, dataSource, params) VALUES ('Marty', 'Hey', 'Hoy', 'temp', COLUMN_CREATE('type', 'tab', 'col0', 'champions', 'col1', 'averageResults'));
Where params' type was defined as a blob, just like the documentation suggests.
The query is accepted, the table updated. If I COLUMN_CHECK the results, it tells me it's fine.
But when I try to select:
"SELECT COLUMN_JSON(params) AS params FROM savedDisplays;
I get a {type: "Buffer", data: Array} containing binary returned to me, instead of the {"type":"tab", "col0":"champions", "col1":"averageResults"} I expect.
EDIT: I can use COLUMN_GET just fine, but I need every column inside the params field, and I need to check the type property first to know what kind of and how many columns there are in the JSON / params field. I could probably make it work still, but that would require multiple queries, as opposed to only one.
Any ideas?
Try:
SELECT CONVERT(COLUMN_JSON(params) USING utf8) AS params FROM savedDisplays
In MariaDB 10 this works at every table:
SELECT CONVERT(COLUMN_JSON(COLUMN_CREATE('t', text, 'v', value)) USING utf8)
as json FROM test WHERE 1 AND value LIKE '%12345%' LIMIT 10;
output in node.js
[ TextRow { json: '{"t":"test text","v":"0.5339044212345805"}' } ]

cannot retain id of first table in left join

I am using sails waterline ORM and i have three tables in my model layer
1-s_class
attributes: {
c_title:{
type:'string',
required: true
},
sec:{
collection:'s_section',
via:"cls"
},
s_session:{
model:'s_session',
columnName:'session'
}
}
2-s_section
attributes: {
sec_title:{
type:'string'
},
sec_priority:{
type:'integer',
required: true
},
cls:{
collection:'s_class',
via:"sec"
}
}
3-s_form
attributes: {
studentName:{
type:'string'
},
s_class:{
columnName:'s_class',
model:'s_class'
},
s_section:{
columnName:'s_section',
model:'s_section'
}
}
i assigned both class and section to student which are saved in s_form table.when i write a query to get a student's record alongwith his class and section.something like this:
s_form.query("SELECT * FROM s_form LEFT OUTER JOIN s_class ON s_form.s_class=s_class.id LEFT OUTER JOIN s_section ON s_form.s_section=s_section.id",function(err,forms){
if(!err)
else{
res.json(forms);
}
});
it populates record of section and class but also affects auto increment primery key of s_form.actually this is because s_section and s_class also have default auto increment primery keys which after populating conflicts and in this case i got id of s_section.
i want to get id of s_form.is there any way to avoid this conflict and overriding of id without affecting default behavior of primery keys????
Note
s_form table contains custom columns means the columns mentioned above are static but it also contain columns which are created at runtime.that's why i can't use built in populate() query method nor i can specify column names like instead of select *.....
Based on your edited / updated post you I would query query to retrieve your column names prior to executing the query so that you can iterate over them and pass the table name as a prefix to each column name. This would allow you to avoid any conflicts.
You can use the following to get column names
SELECT *
FROM `INFORMATION_SCHEMA`.`COLUMNS`
WHERE `TABLE_SCHEMA`='yourdatabasename'
AND `TABLE_NAME`='yourtablename';
You can use this after your dynamic tables are created and save it in a variable so you don't have to keep doing it on every query.
Well, first you can have sails do this for you
s_form.find().populate('').populate('').exec(function(err,forms){/*....*/});
If you want to use query then you need to explicitly name your fields in order to avoid the conflict that will happen.
Instead of SELECT * FROM
You should specific each field so can rename the Id field to avoid these conflicts.
SELECT
s_class.c_title, s_class.id as classId,
s_section.sec_title,s_section.sec_priority,s_section.id as sectionId,
s_form.studentName,s_form.id as formId
FROM FROM s_form LEFT OUTER JOIN s_class ON s_form.s_class=s_class.id LEFT OUTER JOIN s_section ON s_form.s_section=s_section.id