0

需要 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”与主表“Table1”有子关系。我想在以上 2 个表格的标题和描述列中进行搜索。如果在主表“Table1”中找到搜索字符串,则应返回该行以及所有子行。同样,如果在子表行之一中找到搜索字符串,则应返回对应的主表行及其所有子行。为了澄清,请在下面找到结果:

结果:

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

是否可以通过单个查询或其他方式获得结果?

请帮忙。

4

1 回答 1

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 是您需要搜索的字符串。

于 2013-02-15T12:50:53.290 回答