mysql - mysql查询中缺少数据,内部连接需要条件语句

标签 mysql

当我运行以下查询时,我一直遇到丢失数据的问题。 有些产品有特价,存储在表 oc_product_special 中,有些产品有正常价格存储在表 oc_product 中。
我发现它只在表oc_product_special 中有特价时才显示数据。它省略了没有特价而只有正常价格的任何数据。我不确定如何解决这个问题。我可以如何以及在何处添加条件语句或类似

if there is a regular price present and no special price then show regular price and 0 for special price.

<pre><code>SELECT pd.name AS 'Product Name', p.model AS UPC, p.quantity AS 'Quantity', p.price AS 'Regular Price', ps.price AS 'Special Price', p.cost AS 'COST', p.status AS 'Status' FROM oc_product p INNER JOIN oc_product_description pd ON pd.product_id = p.product_id INNER JOIN oc_product_special ps ON ps.product_id = p.product_id INNER JOIN oc_manufacturer m ON p.manufacturer_id = m.manufacturer_id INNER JOIN oc_product_to_category p2c ON p2c.product_id = p.product_id INNER JOIN oc_category c ON c.category_id = p2c.category_id INNER JOIN oc_category_description cd ON c.category_id = cd.category_id WHERE c.category_id = 37 OR c.parent_id = 37 GROUP BY pd.name ORDER BY m.name ASC </code></pre> <p></p>

最佳答案

使用 LEFT JOIN,它将保留连接左侧的记录,即使它们与右侧的任何内容都不匹配也是如此:

SELECT COALESCE(pd.name, 'NA') AS 'Product Name', 
       p.model AS UPC,  
       p.quantity AS 'Quantity', 
       p.price AS 'Regular Price', 
       COALESCE(ps.price, 0.0) AS 'Special Price', 
       p.cost AS 'COST', 
       p.status AS 'Status'
FROM oc_product p
LEFT JOIN oc_product_description pd
    ON pd.product_id = p.product_id
LEFT JOIN oc_product_special ps
    ON ps.product_id = p.product_id
INNER JOIN oc_manufacturer m
    ON p.manufacturer_id = m.manufacturer_id
INNER JOIN oc_product_to_category p2c 
    ON p2c.product_id = p.product_id
INNER JOIN oc_category c 
    ON c.category_id = p2c.category_id
INNER JOIN oc_category_description cd 
    ON c.category_id = cd.category_id
WHERE c.category_id = 37 OR
      c.parent_id = 37
GROUP BY pd.name
ORDER BY m.name

解释:

LEFT JOIN 中,当连接左侧的记录与右侧的任何内容匹配时,右侧的列将全部匹配在结果集中显示为 NULL。我在查询中使用了 COALESCE 函数,如果前者为 NULL,它将有条件地将第一个参数替换为第二个参数。在这种情况下,如果 NULL,特价将被替换为零。我还将它与产品名称一起使用,以防在某些情况下缺少名称。

关于mysql - mysql查询中缺少数据,内部连接需要条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39084733/

相关文章:

mysql - 在 MYSQL 和 UNION 中生成日期范围

php - 将文本文件中的文本插入 MySQL TEXT 列

java - 加载驱动类 com.mysql.jdbc.Driver 失败

php - 如何将多个复选框结果存储到一个 mysql 表中

java - MySQL 和 Java - 插入表时抛出异常

php - 如何使用MySQL全文搜索短语而不是使用LIKE

mysql - grails production jdbc pooling commons-dbcp vs tomcat 7 jndi

php - 如何在zend框架中编写更新查询

java - 如何使用jsp在选择框中根据结果集值设置所选选项

mysql - 为什么我不能在 WHERE 中使用我的列,而我可以在 GROUP BY 中使用?