如何正确编写SQL查询?

时间:2018-07-25 09:46:30

标签: mysql sql

我想找到所有根目录类别均处于活动状态的产品。因此,我根据该文章WITH RECURSIVE and MySQL创建了存储过程 WITH_EMULATOR 以获取根目录类别。 默认查询

SELECT * FROM shop_products 
INNER JOIN shop_category ON (shop_products.category_id=shop_category.id)
WHERE shop_products.active=1
AND (SELECT sc.active FROM shop_category as sc WHERE sc.id = shop_category.parent_id) = 1

然后我尝试在一个查询中做到这一点:

SELECT * FROM shop_products 
INNER JOIN shop_category ON (shop_products.category_id=shop_category.id)
WHERE shop_products.active=1
AND (CALL WITH_EMULATOR(
"EMPLOYEES_EXTENDED",
"
  SELECT ID, PARENT_ID, ACTIVE
  FROM shop_category as sc
  WHERE sc.ID = shop_category.parent_id
",
"
    SELECT P.ID, P.PARENT_ID, P.ACTIVE
    FROM shop_category AS P INNER JOIN EMPLOYEES_EXTENDED C ON C.PARENT_ID = P.ID
",
"
  SELECT ACTIVE
  FROM EMPLOYEES_EXTENDED
  WHERE PARENT_ID = 0
  ORDER BY id
",
0,
""
)) = 1

但是我得到一个错误:

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CALL WITH_EMULATOR(
"EMPLOYEES_EXTENDED",
"
  SELECT ID, PARENT_ID, ACTIVE
' at line 4

我在做什么错?谢谢

shop_category:

id | parent_id | name               | active
1    NULL        Literature           1
2    1           Interesting books    1
3    2           Horrible books       1
4    1           Books to burn        1
5    NULL        Motorized vehicles   0
6    5           Cars                 1
7    6           Motorbikes           1

shop_products:

id | category_id | name
1    7             Cooking for dummies
2    7             Twilight saga
3    7             My grandpa's car

根据此示例,我应该什么也不会得到,因为ID为7的类别的根父级active = 0。

0 个答案:

没有答案