2016-01-11 149 views
0

Table of Categories基於當前行的MySQL查詢行

以上是我的表。現在我想要實現的是查詢,其中type是「main」,包括所有「sub」,其中parent等於當前行的id。我怎樣才能做到這一點?任何幫助將非常感激!

下面是我當前的代碼:

$conn = new PDO("mysql:host=$host;dbname=$db_name",$user,$pass) or die("DB Connection failed!!"); 
$stmt = $conn->prepare('SELECT * FROM tbl_categories WHERE type="main"'); 
$stmt->execute(); 
while($row=$stmt->fetch(PDO::FETCH_ASSOC)) 
{ 
//first loop i should get Electronics, Laptops, Mobile Phones 
//second loop i should get Fashion, Men, Women 
} 

我不想執行while循環中另一個查詢。

+0

在SQL( '正常' 的SQL,即不光標等)被設置爲基礎的。因此,沒有「當前行」。解釋你需要什麼,以及你嘗試過什麼。 – HoneyBadger

+0

當前行是誰?你指的是類型是「主」的行嗎?向我們展示您期待的輸出 –

+0

OP更新.. @AlexandruSeverin –

回答

0

你的問題不是很清楚,但這是你如何在數據庫級別做到這一點。

select * from tbl_categories 
where parent in 
(
    select id from tbl_categories 
    where type='main' 
) 

如果你只是想獲得詳細信息Fashion,然後用這個

select * from tbl_categories 
where parent in 
(
    select id from tbl_categories 
    where type='main' 
    and Category='Fashion' 
) 

SQL小提琴例如

http://sqlfiddle.com/#!9/ea58e/2

0

我覺得在你的數據的錯誤:爲什麼parentfashion = 1?我認爲這是null,與Electronics相同。考慮到,嘗試:

DECLARE @T TABLE (id INT, category VARCHAR(255), Type VARCHAR(50), Parent int) 
; 

INSERT @T 
     (id, category, Type, Parent) 
VALUES (1, 'Electronics', 'Main', NULL) 
,  (2, 'Laptops', 'Sub', 1) 
,  (3, 'Mobile phones', 'Sub', 1) 
,  (4, 'Fashion', 'Main', NULL) 
,  (5, 'Men', 'Sub', 4) 
,  (6, 'Women', 'Sub', 4) 

SELECT  T2.* 
FROM  @T AS T 
INNER JOIN @T AS T2 
     ON T2.Parent = T.id 
WHERE  T.Type = 'Main' 

結果:

id category Type Parent 
2 Laptops Sub 1 
3 Mobile phones Sub 1 
5 Men Sub 4 
6 Women Sub 4