Thursday, September 26, 2019

Mysql : FIND_IN_SET() vs IN()

Orders has this structure:
OrderID     |     attachedCompanyIDs
------------------------------------
   1                     1,2,3
   2                     2,4
And Company has this structure:
CompanyID      |        name
--------------------------------------
    1                 Company 1
    2                 Another Company
    3                 StackOverflow
    4                 Nothing
To get an order's companies names, 
I can do a query as such: SELECT name FROM orders,company WHERE orderID = 1 AND FIND_IN_SET(companyID, attachedCompanyIDs) 
That query works fine, but the following query does not.
 SELECT name FROM orders,company WHERE orderID = 1 AND companyID IN (attachedCompanyIDs) 
Why does the first query work but not the second one?
Explanation :
SELECT  name
FROM    orders,company
WHERE   orderID = 1
        AND companyID IN (attachedCompanyIDs)
attachedCompanyIDs is a scalar value which is cast into INT (type of companyID).
The cast only returns numbers up to the first non-digit (a comma in your case).
Thus,
companyID IN ('1,2,3')  companyID IN (CAST('1,2,3' AS INT))  companyID IN (1)


MySQL: GROUP_CONCAT


By  | August 24, 2014
MySQL GROUP_CONCAT Function
In this tutorial, we will learn how to use the MySQL GROUP_CONCAT function to concatenate strings from a group of values with various options.
The following illustrates the GROUP_CONCAT function:


The maximum length of the return string is 1024 by default.
You can extend the returned value’s length by setting the group_concat_max_len system variable at SESSION or GLOBAL level.
MySQL GROUP_CONCAT Examples
Let’s take a look at the countries table in the sample database.

To get all countries as a (,) string, you use the GROUP_CONCAT function as follows:


To remove the duplicate country names, you have to add the DISTINCT clause as the following query:


To sort the country names before concatenating other than ASC, you have to use the ORDER BY clause as follows:


To change the default separator of the returned string from a comma (,) to a any other, you have to use the SEPARATOR clause as the following query:


Let’s take a look at the states table associated with countries table:


To get country name and all associated state names as concatenated string using the following query:


To get country name and all associated state names with their status(By using CONCAT function) as concatenated string using the following query:


To get country name and all associated state names with their status(By using CONCAT_WS function) as concatenated string using the following query: