简体   繁体   English

PHP SQL 无重复选择和分组

[英]PHP SQL selecting and grouping with no duplicates

I would like to return no duplicate ISBN having the lowest price (see rows in bold).我不想返回具有最低价格的重复 ISBN(请参阅粗体行)。 How can I accomplish that?我怎样才能做到这一点?

isbn price supplier isbn价格供应商

4000 22.50 companyA 4000 22.50 公司A

4000 19.99 companyB 4000 19.99 公司B

4000 22.50 companyC 4000 22.50 公司 C

4001 33.50 companyA 4001 33.50 公司A

4001 45.50 companyB 4001 45.50 公司B

4003 11.99 companyB 4003 11.99 公司B

My query is designed to use OR operators.我的查询旨在使用OR运算符。 That would be welcome to keep this method.欢迎保留此方法。

SELECT * FROM table WHERE isbn = 4000 OR isbn = 4001 OR isbn = 4003 GROUP BY isbn ORDER BY price;

You just need to use the MIN aggregate function:您只需要使用MIN聚合函数:

SELECT isbn, MIN(price)
FROM table 
WHERE isbn = 4000 OR isbn = 4001 OR isbn = 4003 
GROUP BY isbn 
ORDER BY price;

Also, as the comment pointed out, using IN is probably better for your case than a series of OR :此外,正如评论所指出的,使用IN可能比一系列OR更适合您的情况:

SELECT isbn, MIN(price)
FROM table 
WHERE isbn IN (4000, 4001, 4003)
GROUP BY isbn 
ORDER BY price;

You can also do like this你也可以这样做

SELECT DISTINCT tbl.*
FROM tbl tbl
  INNER JOIN
  (
     SELECT isbn,
       MIN(price) as Price
    from tbl
    group by isbn
  ) tbl1
  ON tbl1.isbn = tbl.isbn
  where tbl.isbn = tbl1.isbn and tbl.price = tbl1.Price
  order by isbn

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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