使用单个查询加入嵌套/多查询

How could i join this multi query with just a single mysql query ?

$query = $mysql->query("select rate from postages where city=$city");

if($query->num_rows == 0)
{
    $query = $mysql->query("select rate from postages where subdistrict=$subdistrict");

    if($query->num_rows == 0)
    {
        $query = $mysql->query("select rate from postages where district=$district");           
    }
}

Thanks for your help.

If you wanted to get the exact same result as you have in your example you could do:

SELECT IFNULL(c.rate, IFNULL(d.rate, s.rate)) as rate FROM (
    (SELECT rate, count(*) FROM postages where city = '$city') as c,
    (SELECT rate, count(*) FROM postages where district = '$district') as d,
    (SELECT rate, count(*) FROM postages where subdistrict = '$subdistrict') as s
)

You could also do it another way... Which only runs the district query if where is the city query returns 0 rows, and only runs the subdistrict call if the district query returns 0 rows:

SELECT IFNULL(
        (SELECT rate FROM postages where city = '$city'),
     IFNULL(
       (SELECT rate FROM postages where district = '$district' limit 1),
       (SELECT rate FROM postages where subdistrict = '$subdistrict' limit 1)
     )
) as rate

You could UNION the queries together, but you'd need something in your result so you could tell if it was a city, district or sub district. Something like the following might work, though I've obviously not been able to test it.

(
    SELECT 
        city AS city,
        NULL AS district, 
        NULL AS subdistrict,  
        rate AS rate 
    FROM postages 
    WHERE city=$city
) UNION (
    SELECT 
        NULL,
        district, 
        NULL,
        rate
    FROM postages 
    WHERE city=$city
    AND district=$district
) UNION (
    SELECT 
        NULL, 
        NULL, 
        subdistrict,  
        rate
    FROM postages 
    WHERE city=$city
    AND district=$district
    AND subdistrict=$subdistrict
)

If the result set contains at least one row where city is not null, one where district is not null and one where subdistrict is not null then you've gotten a valid result set.