mysqlnested-select

AND not working with Nested Select sql query


I have an SQL query that selects a minimum value from a column and requires another value to be equal to 1. I am using a nested select and attempting to use an AND statement. However, after adding the AND, the query results with zero results.

SELECT writer_email FROM writerdata_tb WHERE writer_active = 1 AND pending = (SELECT MIN(pending) FROM writerdata_tb) LIMIT 1

How should I fix this code to select WHERE that satisfies both?

writer_email  |  writer_active | pending
-------------   ---------------  --------
email1@mail            0            1
email2@mail            1            3
email3@mail            1            2

The query should result in email3@mail because the record has the least pending and has an active equal to 1.


Solution

  • Try This.

    SELECT writer_email FROM writerdata_tb WHERE writer_active = 1 AND pending = (SELECT MIN(pending) FROM writerdata_tb WHERE writer_active = 1) LIMIT 1
    

    It's due to your second select command it will only select the minimum value regardless the writer_active value