注意:我制作了这张表,因为您没有为您的表提供 SQL DDL。只要给我一些意见,我会编辑答案,直到我们做对为止。
CREATE TABLE priceRequestsProducts AS (
userId INT NOT NULL,
productId INT NOT NULL,
date DATE NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX(userId),
INDEX(productId),
PRIMARY KEY (userId, productId, date),
CONSTRAINT fk_prp_users FOREIGN KEY (userId) REFERENCES (Users.id),
CONSTRAINT fk_prp_products FOREIGN KEY (productId) REFERENCES (Products.id)
) ENGINE=InnoDb;
-- # Shows all dates each user has made a priceRequest for at least one product:
SELECT U.userId, U.firstName, U.lastName, U.username, date
FROM Users U
JOIN priceRequestsProducts as prp ON u.id = prp.id
GROUP BY prp.userId, prp.date;
-- # Shows number of price requests for a product on all dates
SELECT P.id, P.name, count(1) as numRequests, prp.date
FROM Products P
JOIN priceRequestsProducts prp ON prp.productId = P.id
GROUP BY prp.productId, prp.date;