【问题标题】:MySQL query to search string in Master-Child tables and return all rows with Master-Child relationMySQL 查询在 Master-Child 表中搜索字符串并返回具有 Master-Child 关系的所有行
【发布时间】:2013-02-15 12:45:38
【问题描述】:

需要 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

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

请帮忙。

【问题讨论】:

    标签: mysql


    【解决方案1】:

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

    【讨论】:

    • 谢谢米内什。但它不像case1中预期的结果。它应该返回 3 行。
    • 感谢 Minesh 的更新。它有效且易于理解。再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    相关资源
    最近更新 更多