我有两张 table
类别
id category parent_id
1 Electronic
2 Furniture
3 Phone 1
4 LCD 1
5 Watch 1
6 Desk 2
订单
id customer product category_id
1 John Smartphone 3
2 Marry Montior 4
3 King Wood-Desk 6
我想按child_id查找所有电子结果。
像这样..
SELECT product FROM order WHERE category_id = (category.id = 1)
结果
product
Smartphone
Monitor
MySQL中有这样的表达式吗?
最佳答案
您可以为此使用join
。您还需要用反引号封装 order
表名称,因为 order
是保留的(或者您可以重命名该表,以免每次都进行封装)。
SELECT product FROM `order` as o
join category as c
on o.category_id = c.id
WHERE c.parent_id = 1
on
告诉数据库要加入
的数据。 as
创建一个别名,因此不需要每次都写出完整的表名。 (as
也是可选的,我发现它更容易阅读,FROM `order` o
是相同的)
另一种方法可以使用子查询:
SELECT product
FROM `order`
WHERE category_id in (SELECT id FROM CATEGORY where parent_id = 1)
关于mysql - 如何找到另一张 table 上的所有 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47635149/