MySQL相同的id但另一列中的不同值包含具有匹配顺序的针

时间:2016-09-12 00:24:00

标签: mysql sql string

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 |
+-----+-------+---------+

针是大海捞针,或者在字符串中找到子串

对于具有相同pid的每个组,选择一个注释(字符串)包含针顺序后第一个子串针的匹配的组。因此,如果该组中的任何音符包含第一个指针,请选择该指针并继续前进,否则请查看是否包含第二个针等。如果该组没有针匹配,则不要从该pid组中选择任何内容。

通缉输出:

如果这些是上表中使用的针头:

$needle1 = 'foo'  
$needle2 = 'bar' 
$needle3 = 'qux' 


+-----+-------+---------+
|  id |   pid |   note  |
+-----+-------+---------+
|  2  |    66 |  la foo |
|  7  |    27 |  AAfooA |
|  9  |    43 |     qux |
| 11  |    98 |     foo |
+-----+-------+---------+

你将如何实现这一目标?

到目前为止我有什么:

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
        ";

但是这只能找到组中第一个与任何针匹配的

2 个答案:

答案 0 :(得分:0)

可能有更简洁的方法可以做到这一点,但这是一种方式

    CREATE TABLE #temptable
    (  
    id int,  
    pid int, 
    note varchar(20)
    ); 

    INSERT INTO #temptable (id, pid, note) VALUES 
    ('1', '66', 'la qux'),('7', '27', 'AAfooA'),
    ('2', '66', 'la foo'),('8', '43', 'aaa'),
    ('3', '66', 'la bar'),('9', '43', 'qux'), 
    ('4', '66', 'el foo'),('10', '11', 'hehe'),
    ('5', '27', 'aaaaa'),('11', '98', 'foo'),
    ('6', '27', 'barAAA');


    CREATE TABLE #tempNeedle
    (  
    id int,  
    note varchar(20)
    ); 

    INSERT INTO #tempNeedle (id, note)
    VALUES ('1', 'foo'),
    ('2', 'bar'),
    ('3', 'qux');

    Select t5.* from #temptable t5
    INNER JOIN(
    Select t1.id, t1.pid, t1.note,ROW_NUMBER()Over(Partition by t1.PID
    Order by t3.id)  as row
    from #temptable t1
    CROSS APPLY (Select t2.id from #tempNeedle t2 
            Where t1.note LIKE concat('%',t2.note,'%')
            ) t3
            )t4 ON t5.id=t4.id AND t5.pid=t4.pid
    Where t4.row=1

答案 1 :(得分:0)

我认为你可以使用LIKE以及一个简单的连接来逃避:

SELECT t1.id,
       t1.pid,
       t1.note
FROM yourTable t1
INNER JOIN
(
    SELECT pid, MAX(id) AS id
    FROM yourTable
    WHERE note LIKE '%foo%'
    GROUP BY pid
) t2
    ON t1.pid = t2.pid AND
       t1.id  = t2.id