简体   繁体   中英

Table referencing itself , MySQL, primary key and foreign key in same table , select statement

how i select column of categories wich two types SubCat & MainCat from Table referencing itself called cat :

where FOREIGN KEY ( maincat_id ) REFERENCES at ( cat_id ) which is PrimeryKey

table in DataBase:

cat_id    catname       maincat_id   cat_type
1         hello         NULL         1     
2         one           3            2
3         test          1            2
4         te3           3            2

As you see if cat_type=1 so it's SubCat .

i just need table select all the SubCat and the MainCat which it's belong, as this:

catname       Root_name
 one           test        
 test          hello          
 te3           test

more info: We have One table of categories called 'cat', in it There are (Main Categories) and (Sub Categories), which make small tree (just one level depth) .

You can just use a simple inner join for this:

SELECT t1.catname AS Category, t2.catname AS Subcategory 
FROM cat t1 INNER JOIN cat t2
ON t1.cat_id = t2.maincat_id
WHERE t1.cat_type = 1

After all, i hope i understand your question right, and this is what you need.

Fiddle: http://sqlfiddle.com/#!2/94e65/18

you can use self join for this

select c.catname as catname ,m.catname as  Root_name from cat as c, cat as m
where c.maincat_id = m.cat_id &&  c.cat_type=2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM