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

时间:2012-01-21 06:41:30

标签: php mysql

如何只用一个mysql查询加入这个多查询?

$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");           
    }
}

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

您可以将查询联合起来,但是您需要在结果中使用某些内容,以便了解它是城市,区域还是子区域。像下面这样的东西可能会起作用,虽然我显然无法测试它。

(
    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
)

如果结果集至少包含一行,其中city不为null,其中一个where不为null,另一行where subdistrict为null,那么你就得到了一个有效的结果集。

答案 1 :(得分:2)

如果你想获得与你的例子中完全相同的结果,你可以这样做:

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
)

您也可以采用另一种方式...只运行区域查询,如果城市查询返回0行,并且只有区域查询返回0行时才运行子区域调用:

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