我想从2个不同的表中加入查询,我想从两个表中输出

时间:2018-03-16 10:46:57

标签: php mysql database join outer-join

我应用 LEFT JOIN RIGHT JOIN 查询来获取两个表的输出..

有两张表:

Product_list的第一个表..此表包含category_id,它是外键和所有其他产品详细信息..

enter image description here

product_images的第二个表..此表包含product_id,它分别是外键和产品图像..

enter image description here

我想要特定category_id的产品详细信息和产品图片。

我使用此查询但无法正常工作:

SELECT * 
FROM product_list
LEFT JOIN product_images ON product_list.pro_id = product_images.pro_id
WHERE product_list.cat_id =  '.$id.'
UNION 
SELECT * 
FROM product_list
RIGHT JOIN product_images ON product_list.pro_id = product_images.pro_id   

我得到这个输出: enter image description here

API代码

<?php
error_reporting(0);

$response = array();

require_once __DIR__ . '/db_Connect.php';

// check for post data
if (isset($_GET["cat_id"])) {

    $id = $_GET['cat_id'];

    // get a product from products table
    //$q="SELECT * FROM product_list WHERE cat_id ='".$id."' ORDER BY pro_id DESC ";
    $q="SELECT * 
FROM product_list
LEFT JOIN product_images ON product_list.pro_id = product_images.pro_id
WHERE product_list.cat_id =  '.$id.'
UNION 
SELECT * 
FROM product_list
RIGHT JOIN product_images ON product_list.pro_id = product_images.pro_id WHERE product_list.cat_id =  '.$id.'";
    //print($q);
    $res = mysql_query($q);
    print($res);
    //exit();
    if (mysql_num_rows($res) > 0) {

        $responce["category_sub_list"]=array();

        // check for empty result
        while($result = mysql_fetch_array($res)) {

        $product=array();
        $product['pro_id']=$result['pro_id'];
        $product['cat_id']=$result['cat_id'];  
        $product['product_name']=$result['product_name'];
        $product['image']="http://friendzfashionz.com/pandora/admin/Sub_uploads/".$result['image'];
        $product['product_desc']=$result['product_desc'];

        array_push($responce["category_sub_list"],$product);
        } 
         $responce["success"]=1;
         echo json_encode($responce);

    } else {
        // no product found
        $response["success"] = 0;
        $response["message"] = "No user found";

        // echo no users JSON
        echo json_encode($response);
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

1 个答案:

答案 0 :(得分:0)

请尝试此查询。您需要在两个查询中应用where where条件。

SELECT * 
FROM product_list
LEFT JOIN product_images ON product_list.pro_id = product_images.pro_id
WHERE product_list.cat_id =  '.$id.'
UNION 
SELECT * 
FROM product_list
RIGHT JOIN product_images ON product_list.pro_id = product_images.pro_id WHERE product_list.cat_id =  '.$id.'