我在链接 2 个表时遇到问题,其中一个表没有值(value),因此不会显示。为了简化这一点,我创建了一个临时表来显示:
详细信息
ps_product table
product_id name
1 Product 1
2 Product 2
3 Product 3
需要链接另一个表来显示图像路径:
ps_product_details table
details_id product_id properties value
1 1 image_location 1.jpg
2 1 width 10 cm
3 1 height 5 cm
4 2 image_location 2.jpg
5 3 width 9 cm
6 3 height 5 cm
如此处所示,我可以使用LEFT JOIN
加入它们:
SELECT * FROM ps_product
LEFT JOIN ps_product_details ON ps_product.id = ps_product_details.product_id
结果是这样的:
product_id name details_id product_id properties values
1 Product 1 1 1 image_location 1.jpg
1 Product 1 2 1 width 10 cm
1 Product 1 3 1 height 5 cm
2 Product 2 4 2 image_location 2.jpg
3 Product 3 5 3 width 9 cm
3 Product 3 6 3 height 5 cm
到目前为止没有问题。
问题
我不想在加入过程中显示宽度
和高度
,所以我可以做什么 id put WHERE properties = 'image_location'
,但是当我放置它时,它显示:
product_id name details_id product_id properties values
1 Product 1 1 1 image_location 1.jpg
2 Product 2 4 2 image_location 2.jpg
如图所示,产品 3 消失了,因为它没有图像,我不想表明产品 3 不存在,它只是没有图像。
我真正想要的:
product_id name details_id product_id properties values
1 Product 1 1 1 image_location 1.jpg
2 Product 2 4 2 image_location 2.jpg
3 Product 3 null 3 image_location null
details_id
和 values
可能为 null,因为我不知道它的值。但 properties
我已经知道它是 image_location
。这样我就可以不显示图片而不是不显示产品。
我尝试过的
- 来自 @shree.pat18在 here
这是我从中实现的查询:
SELECT * FROM ps_product
LEFT JOIN ps_product_details ON ps_product.id = ps_product_details.product_id
where (properties = 'image_location') or (properties = properties)
它与之前的查询结果相同:
SELECT * FROM ps_product
LEFT JOIN ps_product_details ON ps_product.id = ps_product_details.product_id
有没有解决办法,谢谢您的时间。
最佳答案
将条件放在 ON
子句中,而不是 WHERE
子句中:
SELECT *
FROM ps_product p
LEFT JOIN ps_product_details pd ON p.id = pd.product_id AND pd.properties = 'image_location'
如果您想真正挑剔,您可以在 SELECT
子句中使用 coalesce()
:
SELECT p.product_id, p.name, pd.details_id, p.product_id, coalesce(pd.properties,'image_location') as properties, pd.values
FROM ps_product p
LEFT JOIN ps_product_details pd ON p.id = pd.product_id AND pd.properties = 'image_location'
关于当条件不满足时,MySQL 强制 'WHERE' 显示 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51317192/