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
Related
I know that I can combine multiple columns in mysql by doing:
SELECT CONCAT(zipcode, ' - ', city, ', ', state) FROM Table;
However, if one of the fields is NULL then the entire value will be NULL. So to prevent this from happening I am doing:
SELECT CONCAT(zipcode, ' - ', COALESE(city,''), ', ', COALESCE(state,'')) FROM Table;
However, there still can be situation where the result will look something like this:
zipcode-, ,
Is there a way in MySQL to only have to comma and the hyphen if the next columns are not NULL?
There is actually a native function that will do this called Concat with Separator (concat_ws)!
Specifically, it seems that what you would need is:
SELECT CONCAT_WS(' - ',zipcode, NULLIF(CONCAT_WS(', ',city,state),'')) FROM TABLE;
This should account for all of the null cases you allude to.
However, it is important to note that a blank string ('') is different than a NULL. If you want to address this in the state/city logic you would add a second NULLIF check inside the second CONCAT_ws for the case where a city or a state would be blank strings. This will depend on the database's regard for the blank field and whether you are entering true NULLS into your database or checking the integrity of the blank data before you use it. Something like the following might be slightly more robust:
SELECT CONCAT_WS(' - ', zipcode, NULLIF(CONCAT_WS(', ', NULLIF(city, ''), NULLIF(state, '')), '')) FROM TABLE;
For more, check out the native documentation on concat_ws() here:
https://dev.mysql.com/doc/refman/8.0/en/string-functions.html#function_concat-ws
I think you need something like this
Set #zipcode := '12345';
Set #city := NULL;
Set #state := NULL;
SELECT CONCAT(#zipcode, ' - ', COALESCE(#city,''), ', ', COALESCE(#state,''));
Result: 12345 - ,
SELECT CONCAT(#zipcode, IF(#city is NULL,'', CONCAT(' - ', #city)), IF(#state is NULL,'', CONCAT(', ',#state)))
Result 12345
You need to make the output of the separators conditional on the following values being non-NULL. For example:
SELECT CONCAT(zipcode,
CASE WHEN city IS NOT NULL OR state IS NOT NULL THEN ' - '
ELSE ''
END,
COALESCE(city, ''),
CASE WHEN city IS NOT NULL AND state IS NOT NULL THEN ', '
ELSE ''
END,
COALESCE(state, '')
) AS address
FROM `Table``
Output (for my demo)
address
12345 - San Francisco, CA
67890 - Los Angeles
34567 - AL
87654
Demo on dbfiddle
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));
I have a very specific question.
I have to build a SQL statement that builds a table where some columns are merged together. These columns shall be formatted with delimiters like '\n' or ' ' or ' - '. These delimiters shall be added only if the column before is not empty or null. This should prevent empty lines or unneeded delimiters.
Here is how I started:
SELECT
any_table.table_id,
CONCAT(any_table.text1, '\n', any_table.text2) AS text1_2,
FROM
any_table
WHERE any_table.use = 'true'
This code concats text1 and text2 as a new column text1_2 and uses a line feed as delimiter. The missing part is that line feed shall just be added if any_table.text1 is not null or empty.
Is there an elegant way in doing this with SQL?
thx
Some databases support a very handy function called concat_ws() which does exactly what you want:
CONCAT_WS('\n', NULLIF(any_table.text1, ''), NULLIF(any_table.text2, '')) AS text1_2,
In standard SQL, you can do:
TRIM(LEADING '\n' FROM CONCAT( '\n', || NULLIF(any_table.text1, ''),
'\n' || NULLIF(any_table.text2, '')
)
)
It is possible that your database supports neither of these constructs.
if you'r under SQL SERVER you can use,
SELECT id, CONCAT(colonne1 + ' - ', colonne2) FROM "table"
if you'r under Oracle : you shoul use || for concaténation like
SELECT id, CONCAT(colonne1 || ' - ', colonne2) FROM "table"
I've got a column in a mysql table which contains name information:
"Fred Barney Feuerstein", for example.
Now I need to split this string to create a view with two columns - firstname, lastname.
I know how to select the lastname:
select (SUBSTRING_INDEX(name, ' ', -1)) as lastname from contacts;
But I don't know how to extract all the other information to one new field.
What I'm searching for is something like the SUBSTRING_INDEX for everything except the last field.
//First Item
SUBSTRING_INDEX(`name`, ' ', 1)), 1)
//Second Item
SUBSTRING_INDEX(SUBSTRING_INDEX(`name`, ' ', 2), ' ', -1)), 1)
Per Comments
How to get the first two names...
substr(`name`, 1, (length(`name`) - length(SUBSTRING_INDEX((`name`), ' ', -1))-1));
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');