MYSQL获取主要类别

时间:2017-08-20 14:47:50

标签: mysql relationships

我有以下查询,列出了与其相关的类别和父类别。

t.term_id is the category ID
tx.parent is the ID of category from which they depend from. 
Main Categories have parent id= 0

这是问题,因为查询不显示主要类别而只显示子类别。基本上它只显示父> 0但我需要parent => 0的记录。我已经把它放在了哪里,但是它没有用。

SELECT t.term_id, t.name, tx.parent, tm.name
from mg_terms t

join mg_term_taxonomy tx
on tx.term_id = t.term_id

join mg_terms tm
on tm.term_id = tx.parent

where tx.taxonomy='product_cat'  
ORDER BY `tx`.`parent`  DESC

获取主要类别(parent = 0)的任何帮助?

1 个答案:

答案 0 :(得分:0)

你可以使用UNION select并加入两个结果:

SELECT t.term_id, t.name, tx.parent, tm.name
FROM mg_terms t
JOIN mg_term_taxonomy tx ON tx.term_id = t.term_id
JOIN mg_terms tm ON tm.term_id = tx.parent
WHERE tx.taxonomy='product_cat'  
UNION 
SELECT t2.term_id, t2.name, tx2.parent, null
FROM mg_terms t2
JOIN mg_term_taxonomy tx2 ON tx2.term_id = t2.term_id
WHERE tx2.taxonomy='product_cat' AND t2.parent = 0
ORDER BY parent

或SELECT全部来自mg_terms t和LEFT JOIN mg_terms tm,同样由sagi建议。

SELECT t.term_id, t.name, tx.parent, tm.name
FROM mg_terms t
JOIN mg_term_taxonomy tx ON tx.term_id = t.term_id
LEFT JOIN mg_terms tm ON tm.term_id = tx.parent
WHERE tx.taxonomy='product_cat'  
ORDER BY `tx`.`parent`