我有一张名为fee_category
+------------+--------------+-----------+
| fee_cat_id | fee_cat_name | parent_id |
+------------+--------------+-----------+
| 1 | days scholar | 0 |
| 2 | tuition | 1 |
| 3 | exam | 1 |
| 4 | bus | 1 |
+------------+--------------+-----------+
我想基于parent_id fee_type得到如下
如果parent_id=1
然后
feetype=days scholar
我试过如下
SELECT fee_cat_id
, fee_cat_name
, fee_cat_name IN
( select fee_cat_name
from fee_category
where parent_id !=0
) fee_type
from fee_category;
我的输出看起来像这样
+------------+--------------+----------+
| fee_cat_id | fee_cat_name | fee_type |
+------------+--------------+----------+
| 1 | days scholar | 0 |
| 2 | tuition | 1 |
| 3 | exam | 1 |
| 4 | bus | 1 |
+------------+--------------+----------+
我想要输出如下
+------------+--------------+---------- +
| fee_cat_id | fee_cat_name | fee_type |
+------------+--------------+---------- +
| 1 | days scholar | none |
| 2 | tuition |days scholar|
| 3 | exam |days scholar|
| 4 | bus |days scholar|
+------------+--------------+----------+
答案 0 :(得分:1)
您可以通过表的LEFT JOIN获得此结果,以便将parent_id与fee_cat_name匹配:
SELECT fc1.fee_cat_id, fc1.fee_cat_name, IFNULL(fc2.fee_cat_name, 'none') AS fee_type
FROM fee_category fc1
LEFT JOIN fee_category fc2
ON fc2.fee_cat_id = fc1.parent_id
ORDER BY fc1.fee_cat_id
输出:
fee_cat_id fee_cat_name fee_type
1 days scholar none
2 tuition days scholar
3 exam days scholar
4 bus days scholar
答案 1 :(得分:1)
您可以为表名添加别名。
SELECT a.fee_cat_id, a.fee_cat_name, COALESCE(b.fee_cat_name, 'NONE') as fee_type
FROM fee_category a
LEFT OUTER JOIN fee_category b
ON a.fee_type = b.fee_cat_id;
答案 2 :(得分:0)
您可以使用select
列表中的子查询来实现:
select fee_cat_id,
fee_cat_name,
coalesce((select fee_cat_name from fee_category where fee_cat_id = FC.parent_id), 'none') fee_type
from fee_category FC