我在尝试加入一个表两次时遇到问题。
我有 3 个表:用户、拍卖、出价
Auctions 和 Bids 都包含一个名为 user_ID 的列,它与用户表 ID 相关。
user_ID分别对应Seller(Auction Table)和Winner(Bids Table)
我如何加入所有 3 以便我有一个行: auction_ID, auction_status, seller_name, seller_email, winner_name, winner_email
我尝试进行内部连接但没有成功。
表结构如下:
用户表 ID, 用户登录, 用户邮箱
出价表 ID, 用户身份, 拍卖编号, 创建, 金额
拍卖表 ID, 用户身份, 标题, 结束时间
所以现在我有以下查询:
选择 a.ID 作为 auct_ID,a.status,s.user_email 作为卖家,w.user_email 作为投标人,b.amount,b.created FROM auctions a INNER JOIN 出价 b ON b.auct_ID = a.id INNER JOIN 用户 s ON a.user_ID = s.id INNER JOIN 用户 w ON b.user_ID = w.id WHERE status='active' AND a.end_time < NOW() ORDER BY amount
它为我提供了一个已过期的拍卖的所有出价。我想要所有已过期的拍卖并且只想要最高出价者。
最佳答案
尝试:
SELECT a.*, s.*, w.*, b.* FROM auctions a
INNER JOIN bids b ON b.auction_id = a.id
INNER JOIN users s ON a.user_ID = s.id
INNER JOIN users w ON b.user_ID = w.id
WHERE .....
ORDER BY b.amount DESC LIMIT 1
s
和 w
表别名用于sellers
和winners
关于Mysql在表上加入两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7670164/