i have the following, set of array and a mysql table ,table1
$arr1 = (“A0″,”A1″,”A2″,”A3″,”A4”)
$arr2 = (“B0″,”B1″,”B2″,”B3″,”B4”)
+----+-----------------+------+------+
| id | Col1 | Col2 | Col3 |
+----+-----------------+------+------+
| 0 | A0;B1;B2; | x | 9 |
| 1 | A0;B1;B2;A1;A2; | x | 15 |
| 2 | A0; | x | 7 |
| 3 | B0; | x | 5 |
| 4 | C0; | j | 5 |
+----+-----------------+------+------+
is it possible that i can query the values in my table so that the final output will be something like this
+----+-------+------+
| id | C31T | C32T |
+----+-------+------+
| 0 | 19 | 17 |
+----+-------+------+
C31T and C32T was from this table
+----+------+------ +-------+------+------+
| id | Arr1 | Arr2 | C31 | C32 | tot |
+----+------+-------+-------+------+------+
| 0 | 1 | 2 | 3 | 6 | 3 |
| 1 | 3 | 2 | 9 | 6 | 5 |
| 2 | 1 | 0 | 7 | 0 | 1 |
| 3 | 0 | 1 | 0 | 5 | 1 |
+----+------+-------+-------+------+------+
Following eggyal solution i’m stuck up to this point
SELECT table1.id,
COUNT(DISTINCT arr1.element) AS Arr1,
COUNT(DISTINCT arr2.element) AS Arr2,
COUNT(DISTINCT arr1.element) +
COUNT(DISTINCT arr2.element) AS tot,
(COUNT(DISTINCT arr1.element)/(COUNT(DISTINCT arr1.element)+COUNT(DISTINCT arr2.element)))*col3 AS c31,
(COUNT(DISTINCT arr2.element)/(COUNT(DISTINCT arr1.element)+COUNT(DISTINCT arr2.element)))*col3 AS c32
FROM table1
LEFT JOIN (
SELECT 'A0' AS element
UNION ALL SELECT 'A1'
UNION ALL SELECT 'A2'
UNION ALL SELECT 'A3'
UNION ALL SELECT 'A4'
) arr1 ON FIND_IN_SET(
arr1.element,
REPLACE(table1.Col1, ';', ',')
)
LEFT JOIN (
SELECT 'B0' AS element
UNION ALL SELECT 'B1'
UNION ALL SELECT 'B2'
UNION ALL SELECT 'B3'
UNION ALL SELECT 'B4'
) arr2 ON FIND_IN_SET(
arr2.element,
REPLACE(table1.Col1, ';', ',')
)
WHERE table1.Col2 = 'x'
GROUP BY table1.id
I completely agree with @Kickstart’s comment—you really should normalise your schema:
Then your query would be:
Results:
Without such a normalised schema, the “quite hideous coding” to which (s)he referred would be:
Results:
UPDATE
Following your edit, you merely need to perform an outer query on this existing one:
Results: