How to read MySQL data as JSON - json

I have a database table like this:
Then I want to read data as json object like this:
{
"date_time":"02102019",
"ma_vi_tri":
{
"1a":222,
"0a":111,
"2a":333
}
}
I use this SQL command like this:
MariaDB [mqtt]> SELECT json_object('date_time',date_time,'ma_vi_tri',ma_vi_tri, 'PH', PH) FROM PH where date_time='02102019';
But result output not like I wish.

One option (be careful with performance problems):
SELECT
CONCAT(
'{"date_time": "', `date_time`, '", "ma_vi_tri": ',
REPLACE(
GROUP_CONCAT(
JSON_OBJECT(`ma_vi_tri`, `PH`)
),
'},{',
', '
),
'}'
) `JSON`
FROM
`PH`
WHERE
`date_time` = '02102019'
GROUP BY
`date_time`;
See dbfiddle.

You can create a multi dimensional array and use json_encode
Example:
$ma_vi_tri_arr['1a'] = "222";
$ma_vi_tri_arr['0a'] = "111";
$ma_vi_tri_arr['2a'] = "333";
$result['date_time'] = "02102019";
$result['ma_vi_tri'] = $ma_vi_tri_arr;
echo(json_encode($result));

Related

postgresql check json field contains

I have some json struct, and try check is string contains some value?
I need check, is it words contains 222.
For example:
{
"words": "111, 222"
}
If you want to chack that 222 is available in string or not then try the includes function
OBJECT_NAME.words.includes("222"); //it gives you true
OBJECT_NAME.words.includes("22222"); //it gives you false
You could use LIKE
SELECT ', ' || ('{"words": "111, 222"}'::json->>'words') || ', ' LIKE '%, 222, %';
regexp_split_to_array and the array contains operator #>
SELECT regexp_split_to_array('{"words": "111, 222"}'::json->>'words', ', ') #> ARRAY['222'];
or EXISTS and regexp_split_to_table()
SELECT EXISTS (SELECT *
FROM regexp_split_to_table('{"words": "111, 222"}'::json->>'words', ', ') stt (c)
WHERE stt.c = '222');
db<>fiddle

Generate a JSON string containing the differences in two other JSON strings using T-SQL

Say I have two JSON strings as follows:
[{"RowId":102787,"UserId":1,"Activity":"This is another test","Timestamp":"2017-11-25T14:37:30.3700000"}]
[{"RowId":102787,"UserId":2,"Activity":"Testing the Update function","Timestamp":"2017-11-25T14:37:30.3700000"}]
Both have the same properties but two of the properties in the second string have different values than the first (UserId and Activity). Is it possible, in Azure SQL Database T-SQL, to generate a third JSON string that contains the values in the second string that are different from the first? In other words, I'd like a string returned that looks like this:
[{"UserId":2,"Activity":"Testing the Update function"}]
Also, the solution should assume that the properties in the JSON strings are not known. I need this to be a generic solution for any two JSON strings.
Have not tried this on Azure, but it seems to work on SQL Server 2017
There is probably a more elegant way to get to the final JSON string other than through string manipulation, perhaps we can update the answer as better ways are found.
-- Expected : [{"UserId":2,"Activity":"Testing the Update function"}]
DECLARE #jsonA NVARCHAR(MAX) = '[{"RowId":102787,"UserId":1,"Activity":"This is another test","Timestamp":"2017-11-25T14:37:30.3700000"}]'
,#jsonB NVARCHAR(MAX) = '[{"RowId":102787,"UserId":2,"Activity":"Testing the Update function","Timestamp":"2017-11-25T14:37:30.3700000"}]'
,#result NVARCHAR(MAX) = ''
SELECT #jsonA = REPLACE(REPLACE(#jsonA, ']', ''), '[', '')
,#jsonB = REPLACE(REPLACE(#jsonB, ']', ''), '[', '')
;WITH DSA AS
(
SELECT *
FROM OPENJSON(#jsonA)
)
,DSB AS
(
SELECT *
FROM OPENJSON(#jsonB)
)
SELECT #result += CONCAT (
'"', B.[key], '":'
,IIF(B.[type] = 2, B.[value], CONCAT('"', B.[value], '"')) -- havent checked types other than 1 and 2; think there's a bool type?
,','
)
FROM DSA A
JOIN DSB B ON A.[key] = B.[key]
WHERE A.[value] != B.[value]
SELECT CONCAT('[{', LEFT(#result, LEN(#result) - 1), '}]')

Why is this query returning part of itself in the result?

I've not come across this before. Here's the query:
$query="SELECT
CONCAT_WS(' ',
TRIM(SUBSTRING_INDEX(
SUBSTRING(document, 1, INSTR(document, 'Quickstart') - 1 ),
' ',
-8)
),'Quickstart',
TRIM(SUBSTRING_INDEX(
SUBSTRING(document, INSTR(document, 'Quickstart') + LENGTH('Quickstart') ),
' ',
5)
)
)
FROM documents WHERE MATCH(document)
AGAINST('Quickstart' IN BOOLEAN MODE )";
And here's the resulting array:
[0] => Array
(
[CONCAT_WS(' ',
TRIM(SUBSTRING_INDEX(
SUBSTRING(document, 1, INSTR(document, 'Quickstart') - 1 ),
' ',
-8)
),'Quickstart',
TRIM(SUBSTRING_INDEX(
S] =>
Quickstart for set up. 1. Register your
)
The last part it's returning seems to be correct:
Quickstart for set up. 1. Register your
But why is the query itself returned? Here's the php:
if (!$result = mysql_query($query)) send(mysql_error(),"e");
$hitArray=array();
while ($row=mysql_fetch_array($result, MYSQL_ASSOC) ) { $hitArray[]=$row; }
Thanks for taking a look.
It's not returning itself, it's the key in the array, try to assign an alias to the CONCAT_WS part:
SELECT
CONCAT_WS( ... ) as concatenated
FROM documents WHERE MATCH(document)
AGAINST('Quickstart' IN BOOLEAN MODE )

MySQL, Concatenate two columns

There are two columns in a MySQL table: SUBJECT and YEAR.
I want to generate an alphanumeric unique number which holds the concatenated data from SUBJECT and YEAR.
How can I do this? Is it possible to use a simple operator like +?
You can use the CONCAT function like this:
SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`
Update:
To get that result you can try this:
SET #rn := 0;
SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(#rn := #rn+1,3,'0'))
FROM `table`
You can use mysql built in CONCAT() for this.
SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;
change field name as your requirement
then the result is
and if you want to concat same field using other field which same then
SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1
then this is output
In php, we have two option to concatenate table columns.
First Option using Query
In query, CONCAT keyword used to concatenate two columns
SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;
Second Option using symbol ( . )
After fetch the data from database table, assign the values to variable, then using ( . ) Symbol and concatenate the values
$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;
Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc
In query, CONCAT_WS() function.
This function not only add multiple string values and makes them a single string value. It also let you define separator ( ” “, ” , “, ” – “,” _ “, etc.).
Syntax –
CONCAT_WS( SEPERATOR, column1, column2, ... )
Example
SELECT
topic,
CONCAT_WS( " ", subject, year ) AS subject_year
FROM table
I have two columns:
prenom and nom so to concatenate into a column with name chauffeur_sortant I used this script:
SELECT date as depart, retour, duree_mission, duree_utilisation, difference, observation, concat( tb_chaufeur_sortant.prenom, ' ', tb_chaufeur_sortant.nom) as chauffeur_sortant, concat(tb_chaufeur_entrant.prenom, ' ', tb_chaufeur_entrant.nom) as chauffeur_entrant
FROM tb_passation
INNER JOIN tb_vehicule
ON tb_vehicule.id = tb_passation.id_vehicule
INNER JOIN tb_chaufeur_sortant
ON tb_chaufeur_sortant.id = tb_passation.id_sortant
INNER JOIN tb_chaufeur_entrant
ON tb_chaufeur_entrant.id = tb_passation.id_entrant WHERE tb_vehicule.id = '';
$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');

MySQL: Query for list of available options for SET

In particular table there exists a field of SET type with specific legal values:
personType SET('CUSTOMER','SUPPLIER','EMPLOYEE', 'CONTRACTOR') NOT NULL
Is there any way to query MySQL to get a list of the valid values? In the MySQL interpreter I would just run DESCRIBE someTable; however if there is a more direct method that one could use programmatically without lots of parsing it would be nice.
Thanks.
Now, this simply freaks out, but it is MySQL-only and it works!
SELECT TRIM("'" FROM SUBSTRING_INDEX(SUBSTRING_INDEX(
(SELECT TRIM(')' FROM SUBSTR(column_type, 5)) FROM information_schema.columns
WHERE table_name = 'some_table' AND column_name = 'some_column'),
',', #r:=#r+1), ',', -1)) AS item
FROM (SELECT #r:=0) deriv1,
(SELECT ID FROM information_schema.COLLATIONS) deriv2
HAVING #r <=
(SELECT LENGTH(column_type) - LENGTH(REPLACE(column_type, ',', ''))
FROM information_schema.columns
WHERE table_name = 'some_table' AND column_name = 'some_column');
Just replace "some_table" and "some_column" for your specific table/column, and see the magic!
You will see a weird usage of "information_schema.COLLATIONS" - this is because we need a table there - any table - containing at least N rows, where N is the number of elements in your set.
SELECT
column_type
FROM
information_schema.columns
WHERE
table_name = 'some_table'
AND
column_name = 'some_column';
Returns:
column_type
------------------
set('this','that')
The function below returns an array containing all available options for SET with some parsing but not "lots of parsing"... :)
function get_set_values($table_name, $field_name)
{
$sql = 'DESCRIBE ' . $table_name . ' ' . $field_name;
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
return str_getcsv( trim( substr( $row['Type'], 3 ), '()' ), ',', "'" );
}
Remember that in a set column you may have a combination of values or even an empty value (these are also valid).