SQL for select id 和 childrens 例如在 ( 1,2 ) 然后 select 这 2 个类别的课程
SQL for select id and childrens for example in ( 1,2 ) and then select courses for this 2 categories
我有 2 个这样的 table,我想 select 类别 table 的课程,其中 id,即 1 ,还有以父 1 作为类别的课程。
我尝试类似的方法:
SELECT id,category,( (SELECT id FROM courses WHERE id = 1 OR parent = 1) AS selection) FROM courses
WHERE category IN selection;
但这不是正确的语法,而且我会说我错过了将逗号分隔成字符串来做类似的事情。
table 类别
+----+--------+------+
| id | parent | path |
+----+--------+------+
| 1 | 0 | /1 |
| 2 | 1 | /1/2 |
+----+--------+------+
table 门课程
+----+----------+-----------+
| id | category | shortname |
+----+----------+-----------+
| 1 | 0 | MB2.9.8 |
| 2 | 2 | 1 c |
| 3 | 2 | 2 c |
| 4 | 1 | c 3 |
+----+----------+-----------+
这意味着当我只发送类别 id = 1 时我会有这个,因为 id“2”上的 categories.parent 也有“1”作为父项,所以 selection 的课程 1 和2 个类别
+----+----------+-----------+
| id | category | shortname |
+----+----------+-----------+
| 2 | 2 | 1 c |
| 3 | 2 | 2 c |
| 4 | 1 | c 3 |
+----+----------+-----------+
您需要加入
select CO.*
from Courses CO
inner join Categories CA
on CA.Category = CO.Id
or CA.Category = CO.Parent
where CA.ID = 1
or CA.Parent = 1
或存在一个:
select CO.*
from Courses CO
where exists (
select Id
from Category CA
where (CA.Parent = CO.Category
or CA.Id = CO.Category)
and (CA.ID = 1
or CA.Parent = 1)
)
我有 2 个这样的 table,我想 select 类别 table 的课程,其中 id,即 1 ,还有以父 1 作为类别的课程。
我尝试类似的方法:
SELECT id,category,( (SELECT id FROM courses WHERE id = 1 OR parent = 1) AS selection) FROM courses
WHERE category IN selection;
但这不是正确的语法,而且我会说我错过了将逗号分隔成字符串来做类似的事情。
table 类别
+----+--------+------+
| id | parent | path |
+----+--------+------+
| 1 | 0 | /1 |
| 2 | 1 | /1/2 |
+----+--------+------+
table 门课程
+----+----------+-----------+
| id | category | shortname |
+----+----------+-----------+
| 1 | 0 | MB2.9.8 |
| 2 | 2 | 1 c |
| 3 | 2 | 2 c |
| 4 | 1 | c 3 |
+----+----------+-----------+
这意味着当我只发送类别 id = 1 时我会有这个,因为 id“2”上的 categories.parent 也有“1”作为父项,所以 selection 的课程 1 和2 个类别
+----+----------+-----------+
| id | category | shortname |
+----+----------+-----------+
| 2 | 2 | 1 c |
| 3 | 2 | 2 c |
| 4 | 1 | c 3 |
+----+----------+-----------+
您需要加入
select CO.*
from Courses CO
inner join Categories CA
on CA.Category = CO.Id
or CA.Category = CO.Parent
where CA.ID = 1
or CA.Parent = 1
或存在一个:
select CO.*
from Courses CO
where exists (
select Id
from Category CA
where (CA.Parent = CO.Category
or CA.Id = CO.Category)
and (CA.ID = 1
or CA.Parent = 1)
)