MySQL查询在Master-Child表中搜索字符串并返回具有Master-Child关系的所有行

时间:2013-02-15 12:45:39

标签: mysql

需要MySQL查询帮助。

请在下面找到架构:

Table1
PK_id    Table1_Title    Table1_Description
1        Test1           This is Test1
2        Test2           This is Test2

Table2
FK_id    Table2_Title    Table2_Description
1        Test2           This is Test2  
1        Test3           This is Test3

这里“Table2”与Master表“Table1”处于子关系。我想在上面2个表的Title和Description列中搜索。如果在主表“Table1”中找到搜索字符串,则应返回该行以及所有子行。 Simillarly如果在其中一个子表格行中找到搜索字符串,则应返回相应的主表格行及其所有子表格。澄清请在下面找到结果:

结果:

Case 1:
If searching TEST2 Then

PK_id    Table1_Title    Table1_Description    FK_id    Table2_Title    Table2_Description
1        Test1           This is Test1         1        Test2           This is Test2
1        Test1           This is Test1         1        Test3           This is Test3
2        Test2           This is Test2         NULL     NULL            NULL


Case 2:
If searching TEST1 Then

PK_id    Table1_Title    Table1_Description    FK_id    Table2_Title    Table2_Description
1        Test1           This is Test1         1        Test2           This is Test2
1        Test1           This is Test1         1        Test3           This is Test3


Case 3:
If searching TEST3 Then

PK_id    Table1_Title    Table1_Description    FK_id    Table2_Title    Table2_Description
1        Test1           This is Test1         1        Test2           This is Test2
1        Test1           This is Test1         1        Test3           This is Test3

是否可以使用单个查询或其他内容获得结果?

请帮忙。

1 个答案:

答案 0 :(得分:0)

尝试以下SQL:

更新了SQL

SELECT *
FROM Table1 
LEFT JOIN Table2 ON  Table1.PK_id = Table2.Fk_id
WHERE CONCAT(Table1_Title, ' ', Table1_Description) LIKE 'test2%'
UNION
SELECT *
FROM Table1 INNER JOIN Table2 ON  Table1.PK_id = Table2.Fk_id
WHERE Table1.PK_Id IN 
(
    SELECT Table2.Fk_id
    FROM Table2 
    WHERE CONCAT(Table2_Title, ' ', Table2_Description) LIKE 'test2%'
)

参见 SqlFiddle

另一个变体SQL

SELECT *
FROM Table1 
LEFT JOIN Table2 ON  Table1.PK_id = Table2.Fk_id
WHERE Table1_Title LIKE 'test3%'
OR Table1_Description LIKE 'test3%'
OR Table1.PK_Id IN 
(
    SELECT Table2.Fk_id
    FROM Table2 
    WHERE CONCAT(Table2_Title, ' ', Table2_Description) LIKE 'test3%'
)

参见 SqlFiddle

其中Test2是您需要搜索的字符串。