如何根据单个mysql查询中的列值获取列值?

时间:2016-06-12 18:03:28

标签: mysql

我希望将这两个查询合并为一个:

SELECT category_uri, parent_id FROM categories where ID = 2

// the output of the above query is that category_uri is "men" and parent_id is 1, which i now will use in another query:

SELECT category_uri FROM categories where ID = 1

// the output of this is category_uri "jackets"

我现在可以说基于ID 2,完整类别uri是men/jackets

但是,不是像我这样的两个查询,我将parent_id的值传递给下一个查询,这不能以更简单,更有效的方式完成吗?

3 个答案:

答案 0 :(得分:0)

您可以使用别名

连接表格
SELECT c1.category_uri, c2.category_uri FROM categories c1 left join categories c2 on (c1.parent_id=c2.id) where c1.id = 2

答案 1 :(得分:0)

Select category_uri from categories where ID=2 
union
SELECT category_uri FROM categories where ID = (Select parent_id FROM categories where ID = 2) 

通过这种方式,你可以得到两个结果,男人和夹克。然后你可以随意处理

答案 2 :(得分:0)

查询

SELECT 
  C1.category_uri, C2.category_uri,
  CONCAT(C1.category_uri ,'/',C2.category_uri) AS full_category_uri
FROM 
  categories C1 
LEFT JOIN 
  categories C2 
    ON C1.parent_id=C2.id
WHERE 
  C1.id = 2;

<强>结果

category_uri      category_uri       full_category_uri
-------------------------------------------------------------
men               jackets            men/jackets
  

参考SQLFiddle