MYSQL查询2表,1个JSON输出

时间:2015-09-19 02:47:32

标签: php mysql json

会员表

    +------+-----------+--------+--------------+
    | ID   | emmp id   |username| Is Deleted   |
    +------+-----------+--------+--------------+
    |    1 |      3009 |johnn123|     yes      |
    |    2 |      3005 |bobby133|     no       |
    |    3 |      3015 |adaml542|     no       |
    |    4 |      3999 |admin   |     no       |
    +------+-----------+--------+--------------+

权限表

   +-------------------+-------------+--------------+
   | permission value  | permission  | is_deleted   |
   +-------------------+-------------+--------------|
   |        5234       |   CanEdit   |      no      | 
   |        2562       |   CanAdd    |      no      |
   |        1523       |  CanDelete  |      no      | 
   |        6356       |   CanView   |      no      |
   +-------------------+-------------+--------------+

以上是我上面的结构......

我可以使用下面的代码分别从两个表中请求JSON数据。 (部分代码)

<?php 

        $query = " SELECT column_name FROM table_name;  ";

            $result = mysql_query( $query );
                if ( !$result ) {
                    $ErrorMessage  = 'Invalid query: ' . mysql_error() . "\n";
                    $ErrorMessage .= 'Whole query: ' . $query;
                die( $ErrorMessage );
        }

        $JSON_output = array();
            while ( $row = mysql_fetch_assoc( $result ) )
        {

        $JSON_output[] = array('column_name'        => $row['column_name'], 
                                'column_name'       => $row['column_name'],
                            );
        }

header( "Content-Type: application/json" );

    $JSON_output = json_encode($JSON_output);

echo $JSON_output . "";

mysql_close($Connection);
?>

但是,我很难从两个表中查询

来自会员表的查询。

  "emp_id","username", and filter if "is_deleted" is 'yes' or 'no'.

来自Permissions

的查询

"permission_value", "permission_name",并过滤"is_deleted“是'yes还是'no'

JSON输出= "permission_name","permission_value","emp_id","username"

2 个答案:

答案 0 :(得分:1)

0会导致问题,因为它表示空或null。如果您想节省一些空间,可以使用是/否 y / n is_deleted 列上处理您的查询。这不会引起冲突。

当它们是整数1 +时,你可以使用数值。

答案 1 :(得分:1)

    $query = "
            SELECT      p.permission_type, 
                        m.empid, 
                        m.name

              FROM      members as m

        INNER JOIN      permissions as p

                ON      p.is_deleted = m.is_deleted
            ";

$JSON_output[] = array('Permission Type'        => $row['permission_type'],
                        'Employee ID'           => $row['empid'], 
                        'Full Name'             => $row['name'],
                    );
}