简体   繁体   中英

Select Multiple Book Titles that share the MIN(PRICE) value | MySQL

I have found no other specific problem like this on here.

This is a single table query in MySQL. I have a 'book' table that holds the 'title' and 'price' columns. The problem is to find the minimum book price and display the titles with that minimum value. My problem is that I can only return one title but there is multiple titles with that minimum value. The title my code returns isn't even a valid one, but the first title in the table.

My current code is:

SELECT TITLE,
       MIN(PRICE) AS "PRICE"
FROM book;

You can find the title(s) of the books with the lowest price with a sub query.

SELECT TITLE
FROM   book
WHERE  PRICE = (SELECT MIN(PRICE)
                FROM   book); 

The query in your question is not valid standard SQL and would be rejected by most other RDBMSs.

MySQL does not raise an error ( yet - though this is coming ) but also doesn't guarantee any particular semantics of the result.

You can calculate the minimum price in one subquery, and then find all the books whose price matches that in an outer query.

SELECT a.title, a.price
FROM book AS a
JOIN (SELECT MIN(price) AS minprice
      FROM book) AS b
ON a.price = b.minprice

Another way to write it is:

SELECT titla, price
FROM book 
WHERE price = (SELECT MIN(price) FROM book)

First, create a view that holds the cheapest book (minimum price):

CREATE VIEW minPrice AS
           (SELECT MIN(price) AS price
            FROM book)

Second, join your table with this view like follows:

SELECT book.price, book.title
FROM book
    JOIN minPrice
        ON book.price=minPrice.price

If you are using subqueries like....

SELECT TITLE
FROM   book
WHERE  PRICE = (SELECT MIN(PRICE)
            FROM   book);

these are little slower if are working with a large database as there are two SELECT statements. It will work fine though...You can also go with-:

SELECT title FROM book
ORDER BY price ASC LIMIT 1;

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