连接表值如果记录存在MySQL

时间:2018-05-30 14:10:26

标签: mysql sql database laravel

只有当products表中的记录存在时才需要来自changes表的连接值,其他方式只能从products表返回,我尝试使用LEFT JOIN但是有问题。表格changesproducts也具有相同的结构

    SELECT
    product.*, 
    parent.name, 
    parent.ignored, 
    child.name, 
    child.ignored, 
    changes.* 

    FROM
    products AS product 
    inner join parent_cat AS parent on product.parent_id = parent.ID 
    inner join child_cat AS child on product.category_id = child.ID 
    left join changes AS changes on changes.product_id = product.SKURcrd
    WHERE
       product.slug = 'some slug'

返回的数据如下:

{#389 ▼
  +"parent_id": 3
  +"category_id": 142
  +"product_id": null
  +"slug": "some slug"
  +"SKURcrd": "301832"
  +"product_name": null
  +"product_name_revert": "1911 AIR"
}

表结构看起来像(原理图):

-------------------------        ----------------------------
SKURcrd  |  product_name         product_id  |  product_name
-------------------------        ----------------------------

1 个答案:

答案 0 :(得分:0)

您可以采用两种方法,使用INNER JOIN进行更改,或使用where子句,例如更改位置。 produc_id不为空......如下所示:

SELECT
product.*, 
parent.name, 
parent.ignored, 
child.name, 
child.ignored, 
changes.* 

FROM
products AS product 
inner join parent_cat AS parent on product.parent_id = parent.ID 
inner join child_cat AS child on product.category_id = child.ID 
left join changes AS changes on changes.product_id = product.SKURcrd
WHERE
   product.slug = 'some slug' and changes.product_id is not null