I have 2 tables in my database. One is for orders, and one is for companies.
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?
The first query returns:
name
---------------
Company 1
Another Company
StackOverflow
The second query only returns:
name
---------------
Company 1
Why is this, why does the first query return all the companies, but the second query only returns the first one?
attachedCompanyIDsis a scalar value which is cast intoINT(type ofcompanyID).The cast only returns numbers up to the first non-digit (a comma in your case).
Thus,
In
PostgreSQL, you could cast the string into array (or store it as an array in the first place):and this would even use an index on
companyID.Unfortunately, this does not work in
MySQLsince the latter does not support arrays.You may find this article interesting (see
#2):Update:
If there is some reasonable limit on the number of values in the comma separated lists (say, no more than
5), so you can try to use this query: