使用单个查询获取表数据

时间:2014-02-26 11:01:55

标签: mysql

我想访问name ='vehicle'下的所有数据,以便所有子项和子项都应该进入单个查询

enter image description here

我试过这个查询

SELECT a.CID as MainCategoryID, b.CID as ChildCategoryID, b.parentID
FROM categories a, categories b
WHERE a.CID = b.parentID AND NAME='vehicle'

2 个答案:

答案 0 :(得分:0)

SELECT a.CID as MainCategoryID, b.CID as ChildCategoryID, b.parentID
FROM categories a
LEFT JOIN categories b ON a.CID = b.parentID
WHERE a.NAME = 'vehicle'
ORDER By a.CID

答案 1 :(得分:0)

可能的解决方案应该如下:

SELECT @pv:=cid AS 'cid', name, parentID FROM categories
JOIN (SELECT @pv:=0) tmp
WHERE parentID = @pv

你可以在这里找到一个SQLFiddle:http://www.sqlfiddle.com/#!2/6c75a0/6