简体   繁体   中英

Three tables inner join

I have three tables "user" , "bidding" and "item". I need to find the query in order to get the completed item auctions for a buyer. The way how to find this in my database is the following, item.received=1 AND u.userid=X (this X will be filled in from my PHP which gives the userID of the highest bid). (note that received=1 implies that the deadline is over so this check is not necessary anymore).

Short explanation of the system: it is an auction website, where a user places bids on items and on the users personal account page I want to show the amount of auctions which he bought (and are processed, thus completed).

The 3 tables look like this:

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)
);

The malfunctioning solution I have already is: the result is 3 rows and results being: 3 , 1 , 5. The solution I expect to get only has to be 1 row, containing the number of distinct items.

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

You need to change your query to group on userid instead of item id, and count different items instead of different users.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM