Mysql 如果记录存在,则连接表值
只有当Mysql 如果记录存在,则连接表值,mysql,sql,database,laravel,Mysql,Sql,Database,Laravel,只有当更改表中的记录存在时,我才需要从我的产品表中获取连接值,在其他方式中,仅从产品表获取返回,我尝试使用左连接,但做了一些错误的事情。表更改和产品的结构也相同 SELECT product.*, parent.name, parent.ignored, child.name, child.ignored, changes.* FROM products AS product inner join p
更改表中的记录存在时,我才需要从我的产品
表中获取连接值,在其他方式中,仅从产品
表获取返回,我尝试使用左连接,但做了一些错误的事情。表更改
和产品
的结构也相同
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"
}
表结构如图所示:
有两种方法可以做到这一点,要么使用内部连接到更改,要么使用where changes之类的where子句。产品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
示例数据、期望的结果以及对逻辑的解释都会有所帮助。您的左连接没有本质上的错误,但我怀疑在简化您的查询时,您可能已经消除了问题。请检查WHERE子句谓词以获取对changes
的引用,或发布完整的查询。如果changes
中存在某些记录,是否仍然需要changes
中不存在的记录?在这种情况下,您使用左连接,不存在的记录将仅为null
当更改时,它的请求返回null。未找到product\u id,我正在尝试从only products表中获取数据,如果找不到product\u id OK,我想当您说“只有当changes表中的记录存在时,我才需要我的products表中的连接值”时,我感到困惑我想你只想看看他们是否找到了产品id。示例products.product\u name='Some name',changes.product\u name=NULL,因为changes表是空的,当我使用left join时,我得到的产品名称=NULL,但需要产品名称='Some name'。或者products.product\u name=“Some name”,但是changes.product\u name=“Some name changes”,因为changes表不为空且product\u id=SKURcrd,在这种情况下,我需要获取product\u name=“Some name changes”。有道理?
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