例如,在(1,2)中选择id和子项的SQL,然后为这2个类别选择课程

时间:2016-10-10 07:49:37

标签: mysql sql mariadb

我有这样的2个表,我想选择类别表的课程,其中id,即1,也包括父母1作为类别的课程。

我试着像:

SELECT id,category,( (SELECT id FROM courses WHERE id = 1 OR parent = 1) AS selection) FROM courses 
WHERE category IN selection;

但是这不是一个正确的语法,而且我会说我错过了将字符串逗号分开来做类似的事情。

表类别

+----+--------+------+
| id | parent | path |
+----+--------+------+
|  1 |      0 | /1   |
|  2 |      1 | /1/2 |
+----+--------+------+

表课程

+----+----------+-----------+
| 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”作为父级,所以选择1和2类别的课程

+----+----------+-----------+
| id | category | shortname |
+----+----------+-----------+
|  2 |        2 | 1 c       |
|  3 |        2 | 2 c       |
|  4 |        1 | c 3       |
+----+----------+-----------+

1 个答案:

答案 0 :(得分:0)

您需要加入

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

或EXISTS:

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)
    )