开发者

Join table on itself

开发者 https://www.devze.com 2023-02-19 19:37 出处:网络
I have sufficiently hurt my brain now trying to figure out the logic behind this. I have a table as follows

I have sufficiently hurt my brain now trying to figure out the logic behind this.

I have a table as follows

entry_id | cat_id
       1 | 233
       1 | 234
     开发者_开发百科  1 | 678
       2 | 235
       2 | 453
       2 | 21
       3 | 234
       3 | 123

Is there a way to return in a single query, every category id that is also associated with the same entry ids. So, the select statement would select based on the cat_id, for example 234. What would be returned are the category IDs: 233, 678, 123


SELECT  t2.cat_id
FROM    mytable t1
JOIN    mytable t2
ON      t2.entry_id = t1.entry_id
        AND t2.cat_id <> t1.cat_id
WHERE   t1.cat_id = 234


SELECT cat_id FROM table
  WHERE entry_id IN (SELECT entry_id FROM table WHERE cat_id = 234)
AND cat_id <> 234


select t1.* 
from yourtable t1
join yourtable t2 on (t1.entry_id=t2.entry_id and t1.cat_id<>t2.cat_id)
where t2.cat_id=[your cat]
0

精彩评论

暂无评论...
验证码 换一张
取 消