Table01
with columns
| Id1 | CommaSeparated |
| 1 | 1,2,3 |
| 2 | 4 |
| 3 | 7,8 |
Table02
with columns
| Id2 | SomeValue |
| 1 | Value01 |
| 7 | Value02 |
| 8 | Value03 |
This works: SELECT SomeValue FROM Table02 WHERE Id2 IN(7,8);
. Get Value02 and Value03.
But SELECT SomeValue FROM Table02 WHERE Id2 IN( SELECT CommaSeparated FROM Table01 WHERE Id1 = ? );
does not work (get only Value02). Because it takes only the first character/integer from 7,8
.
Tried this
SELECT SomeValue FROM Table02 WHERE FIND_IN_SET ( Id2, ( SELECT CommaSeparated FROM Table01 WHERE Id1 = 3 ) ) > 0;
But returns no results…
Any ideas how to solve? Or better to create another table where "connect" the both tables ("normalize data")?
2
Answers
Solution, using "linking" table.
LinkingTable
Table01
Table02
And sql like this
SELECT SomeValue FROM Table02 WHERE Id2 IN( SELECT Id2 FROM LinkingTable WHERE Id1 = 3 );
Only need to change code, while inserting into
Table02
, need to insert also intoLinkingTable
and use/takeId1
fromTable01
Or in my case, i anyway need to select data from
Table01
. So another solutionSELECT CommaSeparated FROM Table01 WHERE Id1 = 3;
For example, result name as$arr_result
.Then
If i use
LinkingTable
, i also get "waste of resources". Because inLinkingTable
need to insert modifiedlastInsertId
fromTable02
andId
fromTable01
.The third solution (a bit "crazy").
And
$arr_select = $stmt_select->fetchAll(PDO::FETCH_COLUMN, 0);
Get one dimensional array. May use if know maximum number of values (how many values, so many
union
).At the moment conclusion is that
LinkingTable
solution would be better (less possibility to get something unexpected and, yes, seems in total uses less system resources) ...You can do it using
with
andjson_table
to transfrom comma separated string to rows :Demo here