我正在尝试创建一个可以提取所有与搜索项匹配的项目的MySQL查询。搜索词可以匹配id
或title
- 我已经介绍过了。MySQL:在同一表中取回与当前记录相关的记录
我也想要它返回匹配项可能有的任何孩子。因此,在现阶段,我现在用的是下面的查询:(检索词:“父项”),返回
SELECT * FROM `table` WHERE (`id` LIKE "%parent item%" OR `title` LIKE "%parent item%")
:
id | title | parent_id
------ | ----------- | ---------
15 | parent item | 0
但现在我已经得到陷入试图找出如何返回是这样的:
id | title | parent_id
------ | ----------- | ---------
15 | parent item | 0
34 | child item | 15
45 | child item | 15
58 | child item | 15
我使用PDO连接到数据库,所以要保持一条线是,据我所知,有必要..
任何想法?
编辑:
发现相当多的试验和错误后的解决方案。我已经添加了我的回答如下,但是这是我结束了:
SELECT
t2.id AS id,
t2.title AS title,
t2.parent_id AS parent_id,
t1.title AS parent
FROM
`mc_sets` AS t1
RIGHT JOIN `mc_sets` AS t2
ON
t1.`id` = t2.`parent_id`
WHERE
t2.id LIKE "%parent item%" OR t1.title LIKE "%parent item%" OR t2.title LIKE "%parent item%"
输出:
id | title | parent_id | parent
------ | ----------- | --------- | ----------
15 | parent item | 0 | null
34 | child item | 15 | parent item
45 | child item | 15 | parent item
58 | child item | 15 | parent item
如果您有关于如何改进它,或者不同的解决方案,请随时分享任何想法:d
你说的搜索词可以匹配的ID或标题但在你想要的结果搜索词是匹配什么?除了第一个标题 - 父项 – user3712320
搜索项是与最高结果(id = 15)相匹配的“父项”,然后我想也将所有匹配的id(15)作为父ID 。 –
我用我找到的解决方案更新了我的问题 –