我有一个表名类别
有两个字段
cat_id category_id
199 103
172 122
172 112
112 176
如果cat_id = 172
,我想要一个输出is 122, 112, 176.
我写了这个查询
SELECT f.`category_id` FROM `following_follower_categories` f ,
`following_follower_categories` AS b
WHERE f.`follower_category_id` = `b`.`category_id`
AND f.follower_category_id = 172
显示为空
任何人帮助我
答案 0 :(得分:1)
您需要union all
查询:
select c.category_id
from categories
where cat_id = 172
union all
select c1.category_id
from categories c join
categories c1
on c1.cat_id = c.category_id
where c.cat_id = 172;
请注意,这遵循文本和示例数据中的命名约定,其中名称与示例查询不匹配。
答案 1 :(得分:0)
认为你在where子句中有错误。必须是:
SELECT f.`category_id` FROM `following_follower_categories` f ,
`following_follower_categories` AS b
WHERE f.`follower_category_id` = `b`.`category_id`
AND f.category_id = 172
答案 2 :(得分:0)
使用子查询方法的另一种解决方案
SELECT category_id
FROM following_follower_categories
WHERE cat_id=172 or cat_id in (
SELECT category_id
FROM following_follower_categories
WHERE cat_id=172
)
通常连接比子查询更快,子查询比运算符语句(即联合
)更快看看我是否可以提出加入解决方案:D