从Mysql中的同一个表中的IN()中的子记录中获取父名称

时间:2017-12-13 12:33:16

标签: mysql

我有一张这样的表

tax_id    tax_name          parent_tax_id
1         Sales Tax         0
2         Lodging Tax       0
3.        Resort Tax        1
4.        Hospitality Tax   2

Select tax_name, tax_id from taxes WHERE tax_id IN (3,4).

上面的查询会给我两行id 3& 4,我需要在同一行中获取其父级的tax_name:

SELECT tax_name, tax_id, 
(SELECT tax_name FROM taxes ....) as parent_tax_name 
from taxes WHERE tax_id IN (3,4)

我只需要使用IN(),请告诉我实现此目的的方法。

提前致谢

2 个答案:

答案 0 :(得分:1)

使用自己的联接。 LEFT JOIN因为不是每一行似乎都有一个父

SELECT 
  taxes.tax_name, 
  taxes.tax_id, 
  parent.tax_name AS parent_tax_name 
FROM
  taxes LEFT JOIN taxes AS parent ON taxes.parent_tax_id = parent.tax_id
WHERE 
  taxes.tax_id IN (3,4)

答案 1 :(得分:1)

您可以使用如下所示的连接查询

Select t.tax_name, t.tax_id, tt.tax_name as parent_tax from taxes as t left join taxes as tt on (t.parent_tax_id = tt.tax_id) WHERE t.tax_id IN (3,4)

parent_tax将是父行的tax_name