0

编辑:现在由于某种原因,每个 productid 只出现一次,而不是取决于它有多少变化?有任何想法吗?(我使用的查询是我列出的最后一个查询)

这是我的三表连接查询

SELECT xp.productid, xp.product, xc.classid, xco.optionid, xco.option_name
FROM xcart_products xp
JOIN xcart_classes xc ON xp.productid = xc.productid and xc.class = 'Color'
JOIN xcart_class_options xco ON xc.classid = xco.classid
ORDER by xp.product DESC

现在这里的一切都很好,我得到了大约 2,000 个结果,一切都得到了正确的组织和安排。

现在我想添加第四个表来计算每个 xi.id 的 xi.optionid 的数量,但由于某种原因,我只得到大约 200 个结果并且不知道为什么。这是我试图运行的查询

SELECT xp.productid, xp.product, xc.classid, xco.optionid, xco.option_name, count(xi.optionid) as cnt
    FROM xcart_products xp 
    INNER JOIN xcart_classes xc ON xp.productid = xc.productid AND xc.class = 'Color'
    INNER JOIN xcart_class_options xco ON xc.classid = xco.classid 
    INNER JOIN xcart_images_D xi ON xi.optionid = xco.optionid
    GROUP BY xp.product
    ORDER by xp.product DESC

这是每个表的基本架构

xcart_products -
    + productid*
    + product
xcart_classes - 
    + classid*
    + productid (xcart_products.productid)
xcart_class_options -
    + optionid*
    + classid (xcart_classes.classid)
    + option_name
xcart_images_D - 
    + imageid*
    + optionid (xcart_class_options.optionid)
    + id (xcart_products.productid)

我目前正在使用的查询 -

SELECT xp.productid, xp.product, xc.classid, xco.optionid, xco.option_name, count(xi.optionid) as cnt
FROM xcart_products xp
JOIN xcart_classes xc ON xp.productid = xc.productid AND xc.class = 'Color'
JOIN xcart_class_options xco ON xc.classid = xco.classid
LEFT JOIN xcart_images_D xi ON xi.optionid = xco.optionid
GROUP BY xp.product 
ORDER by xp.product DESC
4

2 回答 2

1

尝试LEFT OUTER JOIN改用。

select xp.productid,
    xp.product,
    xc.classid,
    xco.optionid,
    xco.option_name,
    count(xi.optionid) as cnt
from xcart_products xp
inner join xcart_classes xc on xp.productid = xc.productid
    and xc.class = 'Color'
inner join xcart_class_options xco on xc.classid = xco.classid
left outer join xcart_images_D xi on xi.optionid = xco.optionid
group by xp.product
order by xp.product desc
于 2012-04-05T16:36:54.943 回答
1

在最后一个表上使用左联接。

于 2012-04-05T16:37:17.593 回答