当我运行以下查询时,我一直遇到丢失数据的问题。
有些产品有特价,存储在表 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/