我有三个MySql表: -
我试图做两件事: -
答案 0 :(得分:4)
SELECT
*
FROM
tbl_part part
INNER JOIN tbl_part_to_product p2p ON part.part_id = p2p.part_id
INNER JOIN tbl_product prod ON p2p.product_id =prod.product_id
WHERE part.name = 'whatever'
GROUP BY prod.product_id
HAVING COUNT(*) = 1
要选择只有一个部件的所有产品,只需删除WHERE子句。
如果您不想加入零件表:
SELECT
*
FROM
tbl_product prod
INNER JOIN tbl_part_to_product p2p ON p2p.product_id =prod.product_id
GROUP BY prod.product_id
HAVING COUNT(*) = 1
答案 1 :(得分:0)
让我们解决两个问题:
选择仅包含一个零件的所有产品。
SELECT tbl_product.*
FROM
tbl_product product
INNER JOIN tbl_part_to_product ptop ON ptop.product_id = product.product_id
GROUP BY product.product_id
HAVING COUNT(ptop.part_id) = 1
查找仅具有特定部分的所有产品,因为只有部分。
SELECT tbl_product.*
FROM
tbl_product product
INNER JOIN tbl_part_to_product ptop ON ptop.product_id = product.product_id
INNER JOIN tbl_part part ON ptop.part_id = part.part_id
WHERE part.part_name = 'some name'
GROUP BY product.product_id
HAVING COUNT(ptop.part_id) = 1
如果您从任一查询中获得GROUPing错误,则需要将所有tbl_product字段添加到GROUP。