我正在使用MySql,我的数据库结构如下所示,
Table: product
Structure: product_id - manufacturer_id
Example #1: 30 - 9
Example #2: 31 - 0
表格中没有manufacturer_id 0.
Table: manufacturer
Structure: manufacturer_id - name
Example #1: 9 - Canon
因此,我尝试使用下面的代码,但未列出产品ID 9
SELECT product.product_id, IF(product.manufacturer_id > 0, manufacturer.name, 'Unknown') AS manufacturer FROM product, manufacturer WHERE product.manufacturer_id=manufacturer.manufacturer_id ORDER BY product.product_id ASC
Structure: product_id - manufacturer
Output:
30 - Canon
我需要得到像这样的输出:
Structure: product_id - manufacturer
Output:
30 - Canon
31 - Unknown
我经常搜索并尝试以多种方式进行,但没有成功。 提前谢谢。
答案 0 :(得分:0)
SELECT product.id, ISNULL(manufacturer.name, 'Unknown name') FROM Product INNER JOIN manufacturer ON(Product.manufacturer_id = manufacturer.manufacturer_id)
答案 1 :(得分:0)
你应该尝试LEFT JOIN
这样:
SELECT op.product_id, IFNULL(om.name, 'Unknown')
FROM oc_product op
LEFT JOIN oc_manufacturer om ON op.product_id = om.manufacturer_id
ORDER BY op.product_id ASC
答案 2 :(得分:0)
在测试了两个答案之后,我发现这个答案有效:
SELECT product.product_id, IFNULL(manufacturer.name, 'Unknown') FROM product LEFT JOIN manufacturer ON product.manufacturer_id = manufacturer.manufacturer_id ORDER BY product.product_id ASC
感谢您的帮助。