douba9425 2017-12-23 22:14 采纳率: 100%
浏览 64

如何根据ID将SQL限制为一条记录

I have a table called bids, that have multiple rows.

these all have unique IDs however they have a listingID as well, so everytime it inserts it inserts a new row but with that listingID.

I'm trying to only return one unique result for the ListingID as appose to all the bids in the table , I tried SELECT DISTINCT and group by, but both didn't seem to work.

At the moment this is printing all the records from the table 'bids'

I would like to only print the last record for the listingID column.

$bids = $this->db->query("SELECT bidID,listingID, listing_title, bid_date, username,amount, starting_, sold, vintage, bottles, size, cases, sold_date, bid_type,
FORMAT(`bin`, 0) AS `bin`,
(CASE
WHEN ( SELECT COUNT(*) FROM bids WHERE bid_listing = listingID )
THEN
(SELECT FORMAT(amount,0) FROM bids WHERE bid_listing = listingID  ORDER BY bidID DESC LIMIT 1)
ELSE
FORMAT(`starting_`, 0)
END
) AS `starting`
FROM (`bids`)
JOIN listings ON listingID = bid_listing
JOIN users ON list_uID = userID
WHERE bidder_ID = $userID
ORDER BY bidID DESC");
  • 写回答

1条回答 默认 最新

  • dongwupu5991 2017-12-24 01:56
    关注

    Try this sql. I used b1.* because I don't know what fields you're trying to return.

    $bids = $this->db->query("select b1.* from bids b1
            left join bids b2 on (b1.listingID  = b2.listingID and b1.bidID < b2.bidID
            where b2.bidID is null");
    
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线