使用MYSQL中另一个表的名称对递归表进行SELECT查询

时间:2016-03-16 11:16:54

标签: mysql

我有两张桌子:

  • 首先:( idnames
  • 第二个(递归,用于分层目的):( ididsub

如何显示每个id和idsub的名称?

2 个答案:

答案 0 :(得分:1)

要显示4深度层次结构,您可以在second_table上使用自联接,并从first_table上的子查询中获取名称。你可以尝试这样的事情。

SELECT 
  (SELECT f.names FROM first_table AS f WHERE f.id=s1.id) AS lvl1_names,
  (SELECT f.names FROM first_table AS f WHERE f.id=s2.id) AS lvl2_names,      
  (SELECT f.names FROM first_table AS f WHERE f.id=s3.id) AS lvl3_names,
  (SELECT f.names FROM first_table AS f WHERE f.id=s4.id) AS lvl4_names
FROM second_table AS s1
LEFT JOIN second_table AS s2 ON s1.id = s2.idsub
LEFT JOIN second_table AS s3 ON s2.id = s3.idsub
LEFT JOIN second_table AS s4 ON s3.id = s4.idsub

如果你有更简单的数据结构 first_table (id, names, parent)然后您可以简化它并避免子查询。这样的事情。

SELECT 
  f1.names AS lvl1_names,
  f2.names AS lvl2_names,
  f2.names AS lvl3_names,
  f3.names AS lvl4_names
FROM first_table AS f1
LEFT JOIN first_table AS f2 ON f1.parent = f2.id
LEFT JOIN first_table AS f3 ON f2.parent = f3.id
LEFT JOIN first_table AS f4 ON f3.parent = f4.id

答案 1 :(得分:0)

您可以使用联接查询。

SELECT firstTable.id, names, secondTable.id, idsub FROMfirstTable 
   LEFT JOIN secondTable ON firstTable.id = secondTable.idsub 
   LEFT JOIN thirdTable ON secondTable.subid = thirdTable.id