MySQL:仅在找到子项时添加父行(使用 LIKE,同一张表)

标签 mysql parent children relation

我有这样的表:

id   |    type      |    parent   |   alias
----------------------------------------------
1    |    Type1     |    0        |   animals,fauna
2    |    Subtype11 |    1        |   cat
3    |    Subtype12 |    1        |   goat
4    |    Subtype13 |    1        |   bird,owl
5    |    Type2     |    0        |
6    |    Type3	    |    0        |
7    |    Subtype31 |    6        |   type2 for example,other aliasname
8    |    Subtype32 |    6        |
此表用于实时搜索提示系统,它是简单的父子关系 - 没有更多级别。

我正在使用简单的查询:

SELECT id,type FROM table_name WHERE type LIKE '%something%' OR alias LIKE '%something%'

它按我的预期工作,但我需要扩展它。我不仅需要接收单例 child 行,还需要接收他们的 parent 。

例如。 如果我正在寻找:

(...) WHERE type LIKE '%cat%' OR alias LIKE '%cat%' OR type LIKE '%goat%' OR alias LIKE '%goat%'

我要收的不是单例:

id   |    type      |    parent   |   alias
----------------------------------------------
2    |    Subtype11 |    1        |   cat
3    |    Subtype12 |    1        |   goat

还有他们的 parent (如果有的话!):

id   |    type      |    parent   |   alias
----------------------------------------------
1    |    Type1     |    0        |   animals,fauna
2    |    Subtype11 |    1        |   cat
3    |    Subtype12 |    1        |   goat

与上面完全一样,因为稍后我会检查 parent=0 是否将该行标记为子组。

还有一个技巧 - 我也可以通过 parent 搜索,例如:

(...) WHERE type LIKE '%Type2%' OR alias LIKE '%Type2%'

应该返回:

id   |    type      |    parent   |   alias
----------------------------------------------
5    |    Type2     |    0        |
6    |    Type3     |    0        |
7    |    Subtype31 |    6        |   type2 for example,other aliasname

当然会有大约 500 行具有不同的类型/别名 - 我需要始终将它们返回给 parent 。

虽然这很容易做到,但事实并非如此(或者只是我有一些“脑损伤”:D)

最佳答案

您可以这样做,在表上执行从子记录到父记录的自连接。为两条记录(父/子)添加您的条件。然后根据需要为您希望显示的字段设置别名。

SELECT ch.id, ch.type, prnt.id AS parent_id, prnt.type AS parent_type
FROM   table_name AS ch
       JOIN table_name as prnt
       ON ch.parent = prnt.id
WHERE  (ch.type LIKE '%something%' OR ch.alias LIKE '%something%')
       AND  -- Or "OR" depending on what you are trying to do
       (prnt.type LIKE '%Type2%' OR prnt.alias LIKE '%Type2%');

关于MySQL:仅在找到子项时添加父行(使用 LIKE,同一张表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28438977/

相关文章:

jQuery 选择父级

css - 不工作的 CSS 选择器

java - 如何从 firebase 读取子数据

mysql - 同步两个mysql数据库表

MySQL OR 语句 :The same column or multiple columns?

css - 在忽略父宽度的同时 float 元素彼此相邻?

jquery - “this”父选择器不起作用

jquery - 如何在JQuery中打开和关闭同一个div

PHP Laravel 5.4.21。在第一行 Eloquent 地保存插入

mysql - MariaDB 上的查询非常非常慢