mysql | Format the CONCAT function to have small brackets - mysql

i have select in query
IFNULL(GROUP_CONCAT(DISTINCT CONCAT(ED.dependent_name, ED.date_of_birth))," No Dependents ") AS Dependents
The Result i get is like this..
Data is fine but problem with this is, it look untidy, i want to have date of birth in brackets
e-g for Employee E-02, i want record something like this, means enclose the date in small braces.
Muhammad Zubair (1998-12-15) ,Amir Khan (2000-12-15)
Is there any way i can update the above select statement and get the result like i want to have or any other better way to achieve a good looking result.?
MY Query:
SELECT
`E`.`employee_code` AS Employee_Code,
E.full_name AS NAME,
E.father_name AS Father_Name,
IFNULL(
GROUP_CONCAT(
DISTINCT CONCAT( ED.dependent_name '(', ED.date_of_birth, ')')), " No Dependents " ) AS Dependents
FROM
(`employee` E)
INNER JOIN `employee_project` EP
ON `EP`.`employee_id` = `E`.`employee_id`
INNER JOIN `permanant_contacts` PC
ON `PC`.`employee_id` = `E`.`employee_id`
INNER JOIN `ml_district` MLD
ON `MLD`.`district_id` = `PC`.`district`
LEFT JOIN `dependents` ED
ON `ED`.`employee_id` = `E`.`employee_id`
AND ED.trashed = 0
WHERE `E`.`trashed` = 0
GROUP BY `E`.`employee_id`

Have youy tried
CONCAT(ED.dependent_name, '(', ED.date_of_birth, ')')

Try
CONCAT(ED.dependent_name,CONCAT('(',CONCAT(ED.date_of_birth, ')')))

Related

MySQL using LIKE operator on result of CASE statement and reformatted DATETIME-column

I have a MySQL query where I also need to take a user search-input as a parameter. I was originally going to use the FULLTEXT index to efficiently search all the columns in the table to provide the best search results, but due to limitations in the FULLTEXT index I had to opt for just the LIKE operator. The reason for this is I also need the user to be able to search in the ID column of the table and the DATETIME column, and to my understanding, the FULLTEXT index can only search in columns having a sort of text or character field. Please correct me if I am wrong.
Anyways it works all fine, but in the SELECT part of the query I have 1 CASE function and 2 DATE_FORMAT functions, which the user needs to be able to search in. This is the query I am working with:
SELECT i.itemID, d.dictionaryID, m.modelName, b.brandName, c.categoryName, p1.fname, p1.lname, p2.fname, p2.lname,
date_format(u.startDato, "%W %e. %M - %H:%i") "dateAdded", date_format(u.returDato, "%W %e. %M - %H:%i") "datePlannedReturn",
CASE
WHEN u.accoutPermission = 1 THEN "Moderator"
WHEN u.accoutPermission = 2 THEN "Administrator"
ELSE "User"
END AS permission
FROM item i
INNER JOIN model m ON m.modelID = i.modelID
INNER JOIN dictionaryItem d ON d.dictionaryID = i.dictionaryID
INNER JOIN brand b ON b.brandID = d.brandID
INNER JOIN category c ON c.categoryID = d.categoryID
INNER JOIN person1 p1 ON p1.personID = i.personID
INNER JOIN userAccount u ON u.accountID = d.accountID
INNER JOIN person2 p2 ON p2.personID = d.personID
WHERE u.accountID = x AND i.state = 1 AND (i.itemID LIKE "%search term%" OR c.brandName LIKE "%search term%" OR c.categoryName LIKE "%search term%" OR p1.fname LIKE "%search term%" OR p1.lname LIKE "%search term%"
OR p2.fname LIKE "%search term%" OR p2.lname LIKE "%search term%" OR dateAdded LIKE "%search term%" OR datePlannedReturn LIKE "%search term%"
OR permission LIKE "%search term%")
The problem here is that the LIKE operator on the "permission" column is only searching for the value of the u.accountPermission and not the result of the CASE-function. The same goes for the "dateAdded" and "datePlannedReturn" columns, it compares the search term to the original DATETIME--format and not the reformated date-format. Does anyone know why this happens?
Also, is there any better way to search in all of the returned columns, or do I have to spesify each one individually?
EDIT:
I managed to fix both my issues by using HAVING instead of WHERE for the search-operation and used LOCATE('search term', CONCAT_WS(column1, column2, column3, ...)). This ended up being much cleaner, faster and reliable. Thanks for the help!
Here is the updated Query:
SELECT i.itemID, d.dictionaryID, m.modelName, b.brandName, c.categoryName, p1.fname, p1.lname, p2.fname, p2.lname,
date_format(u.startDato, "%W %e. %M - %H:%i") "dateAdded", date_format(u.returDato, "%W %e. %M - %H:%i") "datePlannedReturn",
CASE
WHEN u.accoutPermission = 1 THEN "Moderator"
WHEN u.accoutPermission = 2 THEN "Administrator"
ELSE "User"
END AS permission
FROM item i
INNER JOIN model m ON m.modelID = i.modelID
INNER JOIN dictionaryItem d ON d.dictionaryID = i.dictionaryID
INNER JOIN brand b ON b.brandID = d.brandID
INNER JOIN category c ON c.categoryID = d.categoryID
INNER JOIN person1 p1 ON p1.personID = i.personID
INNER JOIN userAccount u ON u.accountID = d.accountID
INNER JOIN person2 p2 ON p2.personID = d.personID
WHERE b.brukerID = x AND u.state = 1
HAVING LOCATE('search term', CONCAT_WS(i.itemID, b.brandname, c.categoryName, p1.fname, p1.lname, p2.fname, p2.lname, dateAdded, datePlannedReturn, permission))
Avoid using such a shotgun approach. Instead, craft the search query based on what the user enters. ("If it quacks like a duck, assume it is a duck".)
Pseudo app code:
if it looks like an account number
SELECT id WHERE acct_num = ?
else if numeric input
SELECT id WHERE id = ?
else if it looks like dddd-dd-dd,
SELECT id WHERE date_col = ?
else if ...
...
else if it is long enough to be used in fulltext
SELECT id WHERE MATCH(text1, text2, ...)
AGAINST ("+$string" IN BOoLEAN MODE)
else
your current SELECT (but getting only `id`)
Then put that as a derived table thus:
SELECT lots of columns from lots of tables
FROM (whichever of the above you picked) AS ids
JOINs to get other columns
ORDER BY ...
LIMIT ...
Then declare a FULLTEXT index on just the text columns showing in that MATCH.

COUNT and GROUP_CONCAT in mysql

I am having three tables pcn_type, in_e_s_s__p_c_ns, p_c_n_details. I am trying to concat three different values into single using group concat.
My Query:
SELECT 'browser' AS NAME, CONCAT( '[', CONCAT('{"', pcn_type.name, '",',
COUNT(JPN_ID), '}'), ']' ) AS DATA FROM p_c_n_details INNER JOIN
in_e_s_s__p_c_ns RIGHT OUTER JOIN pcn_type ON pcn_type.name =
p_c_n_details.type AND in_e_s_s__p_c_ns.pcnid=
p_c_n_details.JPN_ID GROUP BY pcn_type.name
Result got:
NAME | DATA
-------------------------------------
browser [{"Design Change",4}]
browser [{"EOL",10}]
browser [{"Process Change",21}]
Expecting Result:
NAME | DATA
--------------------------------------------------------------------
browser [{"Design Change",4},{"EOL",10},{"Process Change",21}]
How to restructure the above query to get the expected result.
use GROUP_CONCAT function
select name,GROUP_CONCAT(DATA SEPARATOR ' ')
from
(
SELECT 'browser' AS NAME, CONCAT( '[', CONCAT('{"', pcn_type.name, '",',
COUNT(JPN_ID), '}'), ']' ) AS DATA FROM p_c_n_details INNER JOIN
in_e_s_s__p_c_ns RIGHT OUTER JOIN pcn_type ON pcn_type.name =
p_c_n_details.type AND in_e_s_s__p_c_ns.pcnid=
p_c_n_details.JPN_ID GROUP BY pcn_type.name
) as T group by name

Mysql Concat is displaying byte array

I am new at mysql. I have code but it is displaying byte array why ?
Sorry about my english :(
SELECT p.city_id,p.name city, CONCAT("[",
GROUP_CONCAT(CONCAT('{id:"', a.id, '", address:"', a.address, '"}')),
"]") As sahalar
FROM cities AS p LEFT JOIN carpet_fields As a ON(p.city_id = a.city_id)
GROUP BY p.city_id, p.name ORDER BY p.city_id
it must be show json data but. The result is
Wrong result
city_id name sahalar
1 ADANA 0x5B7B69643A223236222C20616464726573733A2248757A75
Correct result
city_id name sahalar
1 ADANA [{id:"1A", address:"Huzurevleri Mah.77232 Sk. ADANA / ÇUKUROVA"},{id:"1B", address:"KARSLILAR MAH. 82008. SOK. / MAHFESIGMAZ"}]
I found the solution
SET SESSION group_concat_max_len = 1000000;
SELECT p.city_id,p.name city,
CONCAT("[",
GROUP_CONCAT( CONCAT('{id:"', CAST(a.id as char(10)), '", address:"', a.address, '"}') ),
"]") As sahalar
FROM cities AS p
LEFT JOIN carpet_fields As a ON(p.city_id = a.city_id)
GROUP BY p.city_id, p.name ORDER BY p.city_id

How to consolidate in a query?

I need some help writing a query to consolidate names into a list that are associated with a foreign key. Here's my current query,
select distinct concat(c_first, ' ', c_last) as name, pmt_no
from disbursements d
left join contacts c on c.c_no = d.b_no
where d.ba_no = 1
My result set looks like this
Louis Vaz, 586014
Antionette An, 690682
Brian Cald, 690682
Mark Brian, 3233902
My desired outcome is
Louis Vaz, 586014
Antionette An - Brian Cald, 690682
Mark Brian, 3233902
Please note that both the people with pmt_no 690682 are now joined together with a '-' separating them.
You can use the GROUP_CONCAT() function to achieve what you want:
select group_concat(distinct concat(c_first, ' ', c_last) SEPARATOR ' - ') as name, pmt_no
from disbursements d
left join contacts c on c.c_no = d.b_no
where d.ba_no = 1
group by pmt_no
I think you want group_concat() along with a group_by:
select group_concat(c_first, ' ', c_last separator ' - ') as names,
pmt_no
from disbursements d left join
contacts c
on c.c_no = d.b_no
where d.ba_no = 1
group by pmt_no;

Multiple answers on one line

I have the following tables:
matters(matterid, mattername, refno)
mattersjuncstaff(junked, matterid, staffid, lead)
staff(staffid, staffname)
A matter may have a number of staff associated with it and a number of those staff will be marked as ‘leads’ i.e. they will have a ‘Y’ in the ‘lead’ field.
I wish to show a table that has a list of matters, the matter name and ref no and those staff marked as leads, ideally in a single row. So it would look something like:
reference | mattername | Lead Staff |
ABC1 | matter abc & Co | Fred Smith, Jane Doe, Naomi Watts |
etc
I am using the code below but this only displays one person with the lead field marked Y.
SELECT refno, mattername, matters.matterid, staffname
FROM matters
INNER JOIN matterjuncstaff
USING (matterid)
Inner join staff
using (staffid)
Inner join matterjuncactions
On matterjuncactions.matterid = matters.matterid
WHERE lead = 'Y'
GROUP BY matters.matterid, nickname
Can anyone tell me how I can I get round this?
You want to concatenate values from a join and represent that as a field in the result set. GROUP_CONCAT function is suited for such queries:
SELECT m.matterid, m.refno, m.mattername, GROUP_CONCAT(s.staffname) AS LeadStaff
FROM matters m
LEFT JOIN matterjuncstaff mjs ON mjs.matterid = m.matterid AND lead = 'Y'
LEFT JOIN staff s ON s.staffid = mjs.staffid
GROUP BY m.matterid, m.refno, m.mattername
The join changed to LEFT and lead = 'Y' moved there, otherwise you will lose matters with no lead staffs.
Use INNER JOIN if you only want matters having some lead staff.
I have removed matterjuncactions as you did not give its info.
Use the GROUP_CONCAT() function in mysql to concatenate values from a query into a single string.
For example you could select a row for each matter and append a column with all the concatenated lead staff names as follows:
SELECT m.refno,
m.mattername,
(Select GROUP_CONCAT(distinct staffname SEPARATOR ', ')
from mattersjuncstaff js
join staff s
on s.staffid = js.staffid
where js.lead = 'Y'
and js.matterid = m.matterid) as LeadStaffMembers
FROM matters m
Update
Here is the same example, but with an added column showing staff members that are not the lead.
SELECT m.refno,
m.mattername,
(Select GROUP_CONCAT(distinct staffname SEPARATOR ', ')
from mattersjuncstaff js
join staff s
on s.staffid = js.staffid
where js.lead = 'Y'
and js.matterid = m.matterid) as LeadStaffMembers,
(Select GROUP_CONCAT(distinct staffname SEPARATOR ', ')
from mattersjuncstaff js
join staff s
on s.staffid = js.staffid
where js.lead <> 'Y'
and js.matterid = m.matterid) as NonLeadStaffMembers
FROM matters m