-3
CREATE TABLE    CUSTOMER (
CUSID   VARCHAR(25) NOT NULL,
CNAME   VARCHAR(50),
CONSTRAINT CUSTOMER_PKEY PRIMARY KEY (CUSID),
);

CREATE TABLE    SHOP (
SHOPID  VARCHAR(10) NOT NULL,
ADDRESS VARCHAR(25),
CONSTRAINT SHOP_PKEY PRIMARY KEY (SHOPID),
);

CREATE TABLE    VISIT (
CUSID   VARCHAR(25) NOT NULL,
SHOPID  VARCHAR(10) NOT NULL,
VDATE   DATE        NOT NULL,
CONSTRAINT VISIT_PKEY PRIMARY KEY (CUSID, SHOPID, VDATE),
CONSTRAINT VISIT_FKEY1 FOREIGN KEY (CUSID) REFERENCES CUSTOMER(CUSID),
CONSTRAINT VISIT_FKEY2 FOREIGN KEY (SHOPID) REFERENCES SHOP(SHOPID)
);

如何查找名称为“john”的客户至少访问过 2 次的商店地址?

在 CUSID 所在的商店自然加入访问中选择地址(从 CNAME = 'john' GROUP BY CUSID HAVING COUNT(CUSID) > 2 的客户中选择 CUSID);

我尝试了多种连接,似乎将计数和相等条件放在一起后,我的结果将是 0 行。

4

1 回答 1

1
    SELECT DISTINCT s.address
    FROM shop s 
    JOIN visit v ON s.shopid = v.shopid 
    JOIN customer c ON v.customerid = c.customerid 
    WHERE c.cname = 'John' 
    GROUP BY 
    s.address
    , c.customerid 
    HAVING COUNT(*) > 1
于 2013-05-06T12:36:05.933 回答