我有一个具有这种结构的表:
MyObject( id ,name,category_id,t1,t2,t3,t4);
t1,... tn是表的n个外键
MyType(id,name);
给定一个category_id,我想要一个列表,其中所有MyType的id由MyObjects“使用”给定的category_id。
我可以通过php在一些周期中解析该过程来做到这一点,但我宁愿采用直接的SQL方法。
例如:
MyObject1( 1 ,'q',1,1,2,3,NULL);
MyObject2( 2 ,'w',1,1,2,NULL,NULL);
MyObject3( 3 ,'e',2,5,3,NULL,NULL);
我的预期结果是使用categoy_id === 1:
类型= {1,2,3,5}
我的预期结果是使用categoy_id === 2:
类型= {3,5}
我的预期结果是使用categoy_id === 432:
Types = {}
谢谢
答案 0 :(得分:0)
嗯,我想它比我想象的更简单,这段代码解决了我的需求
SELECT t1
FROM
(SELECT DISTINCT s.t1
FROM MyObject s
WHERE s.category_id = 1 AND s.t1 IS NOT NULL) AS q
UNION
SELECT t2
FROM
(SELECT DISTINCT s.t2
FROM MyObject s
WHERE s.category_id = 1 AND s.t2 IS NOT NULL) AS w
UNION
SELECT t3
FROM
(SELECT DISTINCT s.t3
FROM MyObject s
WHERE s.category_id = 1 AND s.t3 IS NOT NULL) AS e
UNION
SELECT t4
FROM
(SELECT DISTINCT s.t4
FROM MyObject s
WHERE s.category_id = 1 AND s.t4 IS NOT NULL) AS r
UNION
SELECT t5
FROM
(SELECT DISTINCT s.t5
FROM MyObject s
WHERE s.category_id = 1 AND s.t5 IS NOT NULL) AS t
ORDER BY t1 ASC