我从prod_drop中选择所有内容并加入其他2个表以获取更多数据。我不希望重复prod_drop中的任何行,我只想为每个prod_drop行添加1行。
这是我的问题:
SELECT
prod_drop.*
, prod_drop_products.product_id
, cart_product.product_image_sm
FROM
prod_drop
LEFT JOIN
prod_drop_products
ON
prod_drop.prod_drop_id = prod_drop_products.prod_drop_id
LEFT JOIN
cart_product
ON
prod_drop_products.product_id = cart_product.product_id
ORDER BY
prod_drop_id
DESC
结果如下:
prod_drop_id prod_drop_name prod_drop_available product_id product_image_sm
51 Carat Weight yes 4971 S5-3515Y_S.jpg
51 Carat Weight yes 4970 S5-3515Y_S.jpg
51 Carat Weight yes 4969 S5-3515Y_S.jpg
50 Carat Weight yes 4959 S5-3515_S.jpg
50 Carat Weight yes 4960 S5-3515_S.jpg
50 Carat Weight yes 4958 S5-3515_S.jpg
49 Metal Quality yes 3269 Q-8785X-14_S.jpg
49 Metal Quality yes 3270 Q-8785X-14_S.jpg
48 Gold Color yes 1635 1390-Y_S.jpg
48 Gold Color yes 1390 PE0048-12W_S.jpg
但我只希望每个 prod_drop_id 一行(无关紧要),所以基本上我希望我的结果是这样的:
prod_drop_id prod_drop_name prod_drop_available product_id product_image_sm
51 Carat Weight yes 4971 S5-3515Y_S.jpg
50 Carat Weight yes 4959 S5-3515_S.jpg
49 Metal Quality yes 3269 Q-8785X-14_S.jpg
48 Gold Color yes 1635 1390-Y_S.jpg
我该怎么做?
谢谢!
答案 0 :(得分:1)
我想我会在另外两张桌子上尝试MAX(或MIN)。
答案 1 :(得分:1)
从数据中可以看出,prod_drop中每条记录的prod_drop_products中都有不止一条记录。因此,如果您只想在输出中为prod_drop中的每个不同行输出一行,那么您需要从该表中删除输出列,或者确定prod_drop_products中的多行中的哪一行,您希望输出从中获取它的值。查询来自此表的输出列(具体为product_id)如果输出哪个product_id无关紧要(从商业角度来看这没有意义,但是嘿......)那么你可以使用Min或者max ()你喜欢哪个。如果它确实重要,那么请指定您想要使用的逻辑来制定该决定并且可以编辑查询以反映...
假设Min()没问题,你可以:
SELECT pd.prod_drop_id, pd.prod_drop_name, pd.prod_drop_available,
Min(pp.product_id), Min(cp.product_image_sm)
FROM prod_drop pd
LEFT JOIN prod_drop_products pp
ON pp.prod_drop_id = pd.prod_drop_id
LEFT JOIN cart_product cp
ON cp.product_id = pp.product_id
Group By pd.prod_drop_id, pd.prod_drop_name, pd.prod_drop_available
ORDER BY prod_drop_id DESC
答案 2 :(得分:1)
试试这个:
SELECT a.*, b.product_id, c.product_image_sm
FROM prod_drop a
LEFT JOIN prod_drop_products b ON (a.prod_drop_id = b.prod_drop_id)
LEFT JOIN cart_product c ON (b.product_id = c.product_id)
GROUP BY a.prod_drop_id
ORDER BY a.prod_drop_id DESC
答案 3 :(得分:0)
假设您的重复项仅在cart_product
表中,请尝试以下操作:
SELECT pd.*, pdp.product_id, cp.product_image_sm
FROM prod_drop pd
LEFT JOIN prod_drop_products pdp ON pd.prod_drop_id = pdp.prod_drop_id
LEFT JOIN (
select product_id, min(product_image_sm) as product_image_sm
from cart_product
group by product_id
) cp ON pdp.product_id = cp.product_id
ORDER BY pd.prod_drop_id DESC
如果两个表中都有重复项,则需要以下内容:
SELECT pd.*, pdp.product_id, cp.product_image_sm
FROM prod_drop pd
LEFT JOIN (
select prod_drop_id, min(product_id) as product_id
from prod_drop_products
group by prod_drop_id
) pdp ON pd.prod_drop_id = pdp.prod_drop_id
LEFT JOIN (
select product_id, min(product_image_sm) as product_image_sm
from cart_product
group by product_id
) cp ON pdp.product_id = cp.product_id
ORDER BY pd.prod_drop_id DESC