table
+-----+-------+---------+
| id | pid | note |
+-----+-------+---------+
| 1 | 66 | la qux |
| 2 | 66 | la foo |
| 3 | 66 | la bar |
| 4 | 66 | el foo |
| 5 | 27 | aaaaa |
| 6 | 27 | barAAA |
| 7 | 27 | AAfooA |
| 8 | 43 | aaa |
| 9 | 43 | qux |
| 10 | 11 | hehe |
| 11 | 98 | foo |
+-----+-------+---------+
needle is a needle in a haystack, or find substring in string
For each group with the same pid, select one whose note (a string) contains a match for the first substring needle following the needle order. So if any note in that group contains the first needle select that one and move on, else see if any contain second needle etc. If the group has no needle matches, dont select anything from that pid group.
Wanted output:
If these were the needles used with the table above:
$needle1 = 'foo'
$needle2 = 'bar'
$needle3 = 'qux'
+-----+-------+---------+
| id | pid | note |
+-----+-------+---------+
| 2 | 66 | la foo |
| 7 | 27 | AAfooA |
| 9 | 43 | qux |
| 11 | 98 | foo |
+-----+-------+---------+
How would you go about achieving this?
What I have so far:
SQL / php
$needle1 = 'foo';
$needle2 = 'bar';
$needle3 = 'qux';
$sql = "
SELECT id, pid, note
FROM `table`
WHERE INSTR(`note`, '{$needle1}') > 0
OR INSTR(`note`, '{$needle2}') > 0
OR INSTR(`note`, '{$needle3}') > 0
GROUP BY pid
LIMIT 10
";
But this only finds the first one in the group that matches any needle