在一次调用中执行多个mysql查询

时间:2016-12-24 20:58:46

标签: mysql

我想了解如何在一次调用中检索多个mysql值。就像我一样,我有当前的查询,它有效。

SELECT COUNT(*) AS cnt, 
        (3595 * 
            acos(
                cos(radians({$lat1}))
                * cos(radians(lattitude))
                * cos(radians(longitude) - radians({$lon1}))
                + sin(radians({$lat1}))
                * sin(radians(lattitude))
            )
        ) AS distance
        FROM members WHERE person = 'single'
        HAVING distance < 50
    );

稍后我的PHP会调用它:

$single = $row['cnt'];

echo json_encode( array(
    'single' => $single
) );

我的假设表由singlemarrieddivorced组成。在此示例中,我仅对single的人执行了查询。我想知道如何修改我的查询,以便使用相同的mySQl查询对所有这些组执行相同的请求。特别是使用json encode函数。

我看到的一个例子依赖于多个单独的SELECT语句,并结合了$row['cnt']的多个实例。

2 个答案:

答案 0 :(得分:2)

我的版本,非常类似于@ scaisEdge&#39; s。实际上,如果没有比mysqldump -u username --password=`heroku config | grep ^DATABASE | sed 's/.*[a-z0-9][a-z0-9]*:\([a-z][a-z0-9]*\).*/\1/'` -h host dbname | mysql cedric singlemarried更多的类别,则不需要divorced子句。

WHERE

mysqli_result :: fetch_all 可以帮助您获得所需。 http://php.net/manual/en/mysqli-result.fetch-all.php;)

<强>更新

我在JS中做的事情与此类似:

$conn = new mysqli( $host, $user, $pass, $db );

$result = $conn->query( "
    SELECT
        COUNT(*) AS cnt, 
        (3595 * 
            acos(
                cos(radians({$lat1}))
                * cos(radians(lattitude))
                * cos(radians(longitude) - radians({$lon1}))
                + sin(radians({$lat1}))
                * sin(radians(lattitude))
            )
        ) AS distance,
        person -- <-- this gives you the category in the result
    FROM
        members 
    WHERE
        person in ('single', 'divorced', 'married')
    GROUP BY
        person
    HAVING
        distance < 50
" );

$rows =  $result->fetch_all( MYSQLI_ASSOC );

echo json_encode( $rows );

答案 1 :(得分:1)

你可以使用group by

SELECT person, COUNT(*) AS cnt, 
        (3595 * 
            acos(
                cos(radians({$lat1}))
                * cos(radians(lattitude))
                * cos(radians(longitude) - radians({$lon1}))
                + sin(radians({$lat1}))
                * sin(radians(lattitude))
            )
        ) AS distance
        FROM members 
        GROUP By person
        HAVING distance < 50
    );

通过这种方式,您可以获得每个人值的行