如何比较两个表中的值并插入它们是否匹配

时间:2018-05-16 07:35:24

标签: mysql pdo

我有3张桌子

    • id(int)
    • category(varchar)
  1. SUBCAT
    • id(int)
    • category(来自category int的id)
    • sub_category(varchar)
  2. 产物
    • id(int)
    • p_name(varchar)
    • category(varchar)
    • category_id(int)
    • sub_category(varchar)
    • sub_category_id(id)
  3. 我需要检查cat.category == product.category和subcat.sub_category  == product.sub_category然后将cat和subcat中的id插入到产品category_id,sub_category_id

    SELECT p.*, c.category AS category_name, s.sub_category AS subcategory_name
                                            FROM product AS p
                                            LEFT JOIN subcat AS s ON p.sub_category = s.sub_category 
                                            LEFT JOIN cat AS c ON p.category = c.category
    

1 个答案:

答案 0 :(得分:3)

期待您的架构

您似乎正在根据类别和子类别的值查找表产品category_id,sub_category_id列的更新

您可以使用带连接的更新

update product p 
inner join subcat AS s ON p.sub_category = s.sub_category 
inner join cat AS c ON p.category = c.category 
set p.category_id = c.id, 
    p.sub_category_id = s.id