Complex concatenation on GROUP BY string - mysql

I have the following query:
SELECT
title_imdb_id, person_imdb_id, role_type_id, role_name
FROM
mturk_imdbcredit
WHERE
title_imdb_id=1
Which gives me:
title_imdb_id person_imdb_id role_type_id role_name
1 1588970 Actor Herself
1 5690 Director NULL
I would like to group by the title_imdb_id and concatenate the three fields separated by a : and the rows separated by a ,. The end result should be:
1588970:Actor:Herself, 5690:Director:
Is this possible to do in SQL ?

You can use a field concat in addition to a GROUP_CONCAT:
SELECT
GROUP_CONCAT(
CONCAT (
person_imdb_id, ':', role_type_id, ':', IFNULL(role_name, '')
) SEPARATOR ', '
)
FROM
mturk_imdbcredit
GROUP BY
title_imdb_id
Which gives me:
1588970:Actor:Herself, 5690:Director:

Related

How can I achieve SQL query in GROUP_CONCAT to seperate with ',' and ends with '&'

I'm trying to achieve and SQL statement to query to GROUP_CONCAT all the classes which separates with commas if more than 2 classes and also ends with '&' for the last class and If no comma if only 1 class.
SELECT `tbl_perfumes`.`pk_int_perfumeID` AS `Perfume ID`,
GROUP_CONCAT(DISTINCT `tbl_notes`.`txt_noteName` ORDER BY `tbl_notes`.`txt_noteName` ASC SEPARATOR ',
' ) AS `Notes` FROM `tbl_notes` JOIN `tbl_perfumeNotes`
ON `tbl_notes`.`pk_int_noteID` = `tbl_perfumeNotes`.`fk_int_noteID`
JOIN `tbl_perfumes` ON `tbl_perfumeNotes`.`fk_int_perfumeID` = `tbl_perfumes`.`pk_int_perfumeID`
WHERE `tbl_perfumes`.`pk_int_perfumeID`=1
GROUP BY `tbl_perfumes`.`pk_int_perfumeID`
ie; (1)
(1 & 2)
(1, 2, 3 & 4)

How to write "replace" once in a SQL query having 3 times like operator

Here is my sql query. I don't want to write the "replace" 3 times. How can I optimize it ?
select * from table1 where col1='blah' AND
(
replace(replace(col2,'_',' '),'-',' ') LIKE ? OR
replace(replace(col2,'_',' '),'-',' ') LIKE ? OR
replace(replace(col2,'_',' '),'-',' ') LIKE ?
)
You could use subquery:
SELECT *
FROM (
select *, replace(replace(col2,'_',' '),'-',' ') AS r
from table1
where col1='blah'
) s
WHERE r LIKE ? OR r LIKE ? OR r LIKE ?
Or LATERAL:
select *
from table1
,LATERAL(SELECT replace(replace(col2,'_',' '),'-',' ') AS r) s
where col1='blah'
and (s.r LIKE ? OR s.r LIKE ? OR s.r LIKE ?)
db<>fiddle demo
I prefer the second approach because there is no need for introducing outer query. This feature was added in version 8.0.14.
Related:
PostgreSQL: using a calculated column in the same query
CROSS/OUTER APPLY in MySQL
In MySQL you can use a column alias in the HAVING clause even without any aggregation:
select *, replace(replace(col2,'_',' '),'-',' ') as col2_replace
from table1
where col1='blah'
having col2_replace like ?
or col2_replace like ?
MySQL has a tendency to materialize subqueries -- not only is this overhead for reading and writing a temporary table but it can also affect the use of indexes in a more complicated query.
Here are three alternative solutions that do not require subqueries.
If ? does not contain wildcards, then the simplest method is:
replace(replace(col2, '_', ' '), '-', ' ') in (?, ?, ?)
If it does, then change logic to use a single regular expression pattern:
replace(replace(col2, '_', ' '), '-', ' ') regexp ?
You can also explicitly adjust the pattern in the query:
replace(replace(col2, '_', ' '), '-', ' ') regexp
concat('(',
replace(replace(?, '_', '.'), '%', '.*'), ')|(',
replace(replace(?, '_', '.'), '%', '.*'), ')|(',
replace(replace(?, '_', '.'), '%', '.*'), ')'
)

How to get multiple value in one variable with ' '

How i can get value like this in a variable 'TFSEP-2019','TFjul-2018','TFJun-2018' without spaces.
SELECT s.house, s.grade, s.homeroom AS Campus
FROM student s,fees_jrl f
WHERE s.studnum = f.studnum AND
f.name IN (' TFJun-2018 TFJul-2018 ') AND
f.trans_type= 'chg' AND
f.paid_id is NULL AND s.house LIKE '%'
GROUP BY s.house
I am getting like this ('TFJun-2018 TFJUL-2018 TFSEP-2019') but I want like ('TFSEP-2019','TFjul-2018','TFJun-2018') please help
You may refer the following statements with like operators, whenever you need quotes('), use doubled-quotes('') :
create table tab ( Id int, expression varchar(100));
insert into tab values(1 ,'TFJun-2018 TFJUL-2018 TFSEP-2019');
insert into tab values(2,'''TFJun-2018'',''TFJUL-2018'',''TFSEP-2019''');
select * from tab where expression like '''TFJun-2018''%';
Id expression
2 'TFJun-2018','TFJUL-2018','TFSEP-2019'
or
select * from tab where expression like '''TFJun-2018'',''TFJUL-2018''%';
Id expression
2 'TFJun-2018','TFJUL-2018','TFSEP-2019'
or
select * from tab where expression like '''TFJun-2018'',''TFJUL-2018'',''TFSEP-2019''%';
Id expression
2 'TFJun-2018','TFJUL-2018','TFSEP-2019'
Rextester Demo
You can use like for strings
% means any chars, _ means one char
So doing
F.name like %2018%
Will give you all of 2018..
use explicit join and concat
SELECT
concat( concat( concat( concat("'",s.house),"'"),concat( concat("'",s.grade),"'")),
concat( concat("'",s.homeroom),"'"))
FROM student s join fees_jrl f
on s.studnum = f.studnum
where f.name IN (' TFJun-2018 TFJul-2018 ') AND
f.trans_type= 'chg' AND
f.paid_id is NULL AND s.house LIKE '%'
I think you dont need group by as you have no aggregation function

how to join or split columns VARCHAR type in same table

Mysql:
I have table : id, First_name (varchar), Last_name (varchar);
How to convert to table : id, Name (varchar); ?
And
table : id, Address (varchar);
convert to :
table : id, Street_name(varchar), house_number(varchar), room_number(varchar);
In other words, how to join or split columns VARCHAR type?
1- The joining is straitforward. If we assume your first table is "originalTable", then you need two concat the two fields and put everything in a new table, named t1 for example:
Select into t1 id, concat(First_name, last_name) as Name
From originalTable
The new table, t1, will be automatically created with two fields (int and varchar).
2- For the splitting, provided that there are three non-empty sub-fields (Street_name, House_number and Room_number), you can use the following SQL code:
SELECT
substring(Address, 1, locate(' ', Address)-1) as Street_name,
substring(
substring(Address FROM locate(' ', Address)+1),
1,
locate(' ', substring(Address FROM locate(' ', Address)+1))-1
) as House_number,
substring(
substring(
Address FROM locate(' ', Address)+1
)
FROM locate(
' ',
substring(Address FROM locate(' ', Address)+1)
)+1
)
as Room_number
From t1
For the details of the two string functions (substring and locate) used here, see MySQL documentation about string functions:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html

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');