我是MYSQL的新手,并且正在努力形成一个连接两个表并返回唯一产品行的查询。
表 product
:
╔══════════════════════════════╦══════════╦════════════╦════════════════════╗
║ ref ║ brand ║ mpn ║ sku ║
╠══════════════════════════════╬══════════╬════════════╬════════════════════╣
║ 0001___DOGICLON___912-101242 ║ DOGICLON ║ 912-101242 ║ 000000000001082649 ║
║ 0002___DOGICLON___912-101242 ║ DOGICLON ║ 912-101242 ║ 912-101242 ║
║ 0003___Dogiclon___912-101242 ║ Dogiclon ║ 912-101242 ║ 912-101242(R400) ║
║ 0005___Dogiclon___912-101242 ║ Dogiclon ║ 912-101242 ║ MILT-R400 ║
╚══════════════════════════════╩══════════╩════════════╩════════════════════╝
表 inventory
:
╔══════════════════════════════╦═══════╦═════════╦══════════╗
║ ref ║ scost ║ instock ║ location ║
╠══════════════════════════════╬═══════╬═════════╬══════════╣
║ 0001___DOGICLON___912-101242 ║ 53.68 ║ 24 ║ WA ║
║ 0001___DOGICLON___912-101242 ║ 53.68 ║ 0 ║ CA ║
║ 0002___DOGICLON___912-101242 ║ 61.00 ║ 121 ║ WA ║
║ 0003___Dogiclon___912-101242 ║ 53.53 ║ 100 ║ WA ║
║ 0003___Dogiclon___912-101242 ║ 53.53 ║ 0 ║ NY ║
║ 0003___Dogiclon___912-101242 ║ 53.53 ║ 20 ║ MA ║
║ 0003___Dogiclon___912-101242 ║ 53.53 ║ 2 ║ CA ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║ 5 ║ IN ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║ 5 ║ MA ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║ 5 ║ WA ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║ 5 ║ NY ║
║ 0005___Dogiclon___912-101242 ║ 56.00 ║ 2 ║ CA ║
╚══════════════════════════════╩═══════╩═════════╩══════════╝
我猜pseduo代码将是:
SHOW all products
WHERE
instock (any location) > 0 AND
(cost > 10 AND cost < 2000)
ORDER BY
cost asc
备注:
ref
是每个供应商的唯一商品brand
和mpn
查找需要
不区分大小写预期结果:
╔══════════╦══════════╦════════════╦══════════════╦══════════════╦═══════════════════════════╗
║ ref ║ brand ║ mpn ║ sku ║ scost ║ instock ║
╠══════════╬══════════╬════════════╬══════════════╬══════════════╬═══════════════════════════╣
║ whatever ║ Dogiclon ║ 912-101242 ║ based on ref ║ based on ref ║ based on ref and location ║
╚══════════╩══════════╩════════════╩══════════════╩══════════════╩═══════════════════════════╝
这就是我正在尝试的:
SELECT DISTINCT
product.ref,
product.brand,
inventory.scost,
inventory.instock
FROM
product
JOIN inventory ON inventory.ref = product.ref
WHERE
inventory.instock > 1
AND ( app.inventory.scost >= 10 AND app.inventory.scost <= 2000 )
GROUP BY
product.ref
答案 0 :(得分:0)
如果您按产品中的唯一列进行分组,似乎是ref,则distinct将不会按照您的意愿执行。 DISTINCT负责每个返回行的唯一性(返回所有值)。在这种情况下,为了获得每个产品参考结果的一行,您需要删除不同的部分,将product.mfr添加到group by并聚合非分组的列,如下所示:
SELECT
product.ref,
product.mfr,
group_concat(inventory.scost) as scost,
group_concat(inventory.instock) as instock,
FROM
product
JOIN inventory ON inventory.ref = product.ref
WHERE
inventory.instock > 1
AND ( app.inventory.scost >= 10 AND app.inventory.scost <= 2000 )
GROUP BY
product.ref, product.mfr
如果你想确保scost和instock的正确排序,只需在group_concat中包含ordered子句即:
group_concat(column order by column1, [...])