我有三个表“user”,“bidding”和“item”。 我需要找到查询才能获得买家的已完成项目拍卖。如何在我的数据库中找到它的方法如下,item.received = 1 AND u.userid = X(这个X将从我的PHP填写,它给出了最高出价的用户ID)。 (请注意,收到= 1表示截止日期已结束,因此不再需要此检查)。
该系统的简短说明:它是一个拍卖网站,用户在物品和用户个人账户页面上出价,我想要显示他购买的(并经过处理,完成)的拍卖数量。 / p>
3个表格如下:
CREATE TABLE user (
userid INT NOT NULL AUTO_INCREMENT,
username CHAR(30) NOT NULL UNIQUE,
password CHAR(32) NOT NULL,
firstname CHAR(30) NOT NULL,
lastname CHAR(30) NOT NULL,
gender CHAR(1) NOT NULL,
email CHAR(50) NOT NULL UNIQUE,
birthdate DATE NOT NULL,
addressid INT NOT NULL,
picture CHAR(50),
lastlogin TIMESTAMP NOT NULL,
role CHAR(30),
paymentid INT NOT NULL,
PRIMARY KEY (userid),
FOREIGN KEY (addressid)
REFERENCES address(addressid),
FOREIGN KEY (paymentid)
REFERENCES payment(paymentid)
);
CREATE TABLE item (
itemid INT NOT NULL AUTO_INCREMENT,
name CHAR(40) NOT NULL,
description CHAR(255) NOT NULL,
originalpurchasedate DATE,
deadline TIMESTAMP NOT NULL,
minprice DOUBLE,
received BOOLEAN NOT NULL,
dateadded TIMESTAMP NOT NULL,
openbidding BOOLEAN NOT NULL,
categoryid INT NOT NULL,
ownerid INT NOT NULL,
PRIMARY KEY (itemid),
FOREIGN KEY (categoryid)
REFERENCES category(categoryid),
FOREIGN KEY (ownerid)
REFERENCES user(userid)
);
CREATE TABLE bidding (
userid INT NOT NULL,
itemid INT NOT NULL,
amount DOUBLE,
bidtime TIMESTAMP NOT NULL,
FOREIGN KEY (userid)
REFERENCES user(userid),
FOREIGN KEY (itemid)
REFERENCES item(itemid)
);
我已经出现故障的解决方案:结果是3行,结果是:3,1,5。我期望获得的解决方案只需要1行,包含不同项目的数量。
SELECT DISTINCT COUNT(u.userid) FROM `item` i
INNER JOIN `bidding` b ON i.itemid = b.itemid
INNER JOIN `user` u ON b.userid = u.userid
WHERE i.received=1 AND u.userid=2
GROUP BY i.itemid
答案 0 :(得分:1)
您需要将查询更改为在userid而不是item id上进行分组,并计算不同的项目而不是不同的用户。
SELECT DISTINCT COUNT(i.itemid) FROM `item` i
INNER JOIN `bidding` b ON i.itemid = b.itemid
INNER JOIN `user` u ON b.userid = u.userid
WHERE i.received=1 AND u.userid=2
GROUP BY u.userid