通过多列上的条件从SELECT中删除结果

时间:2017-04-25 00:21:22

标签: mysql sql

所以我有这个产品的供给

id man sup product
1  1   1   MacBook
2  1   2   iMac
3  2   1   Windows
4  2   2   Office

然后是制造商的表格

id manufacturer
1  Apple
2  Microsoft

和供应商

id supplier
1  TechData
2  Westcoast

然后,出于某些原因,我不想让某个供应商展示制造商的产品,即:

id man sup comment
1  2   1   TechData aren't allowed to sell Microsoft 
2  1   2   hide all Apple products from Westcoast

在纯SQL中,有没有办法只显示通过我的过滤器的产品,在这种情况下是MacBook和Office?我相信这不仅仅是WHERE NOT (x AND y),因为结果会列出剩余的组合。

非常感谢!

2 个答案:

答案 0 :(得分:1)

这只是Return row only if value doesn't exist的变体,除了您在两列上加入。

SELECT p.product, m.manufacturer, s.supplier
FROM products AS p
JOIN manufacturers AS m ON m.id = p.man
JOIN suppliers AS s ON s.id = p.sup
LEFT JOIN filter AS f ON p.man = f.man AND p.sup = f.sup
WHERE f.id IS NULL

DEMO

答案 1 :(得分:0)

你可以试试这个,交配:

首先,为您的自定义制造商 - 供应商过滤器创建temporary/real容器:

-- pivot temp/real table for suppliers - manufacturers
DROP TEMPORARY TABLE IF EXISTS `manufacturers_suppliers`;
CREATE TEMPORARY TABLE `manufacturers_suppliers` (
    `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
    `manufacturer_id` INT(11) UNSIGNED, 
    `supplier_id` INT(11) UNSIGNED,
    PRIMARY KEY (`id`),
    UNIQUE KEY (`manufacturer_id` ASC, `supplier_id` ASC)
);
-- populate pivot table
INSERT INTO `manufacturers_suppliers` (`manufacturer_id`, `supplier_id`)
VALUES 
    -- TechData aren't allowed to sell Microsoft 
    (2, 1), 
    -- hide all Apple products from Westcoast
    (1, 2);

之后,使用容器的内容,您只需要为结果集创建标准查询。

-- create result
SELECT 
    p.id, p.product,        # show product detail
    s.id, s.supplier,       # show supplier detail
    m.id, m.manufacturer    # show manufacturer detail
FROM
    products p
    INNER JOIN suppliers s ON s.id = p.sup
    INNER JOIN manufacturers m ON m.id = p.man
    LEFT JOIN `manufacturers_suppliers` ms ON 
        ms.manufacturer_id = man.id
        AND ms.supplier_id = sup.id
WHERE ms.id IS NULL;

因此,每当您对过滤器进行更新时,您只会更新records而非实际的query script。干杯