MYSQL,PHP)使用UNION ALL

时间:2018-10-06 20:17:51

标签: php mysql union

我需要循环两个不同的表并从所有列中获取值。

我尝试使用UNION ALL解决我的问题。

代码如下:

if(isset($_GET['country'])){
        $sql = "SELECT name, capital, population,description,null FROM countries WHERE name ='France'

        UNION ALL
             SELECT null,null,null,null,attraction_name FROM attraction_list WHERE country_name='France'
        ";
        mysqli_select_db($conn,'travelapp') or die("database not found");
        $result = mysqli_query($conn,$sql);
        if($result){
            $countryName;$capital;$population;$description;$attraction;
            while($row = $result->fetch_row()){
                $countryName=$row[0];
                $capital=$row[1];
                $population=$row[2];
                $description=$row[3];
                $attraction=$row[4];
            }
            $resultArray = array(
                'country'=>$countryName,
                'capital'=>$capital,
                'population'=>$population,
                'description'=>$description,
                'attraction'=>$attraction
            );
            echo json_encode($resultArray);
        }
    }

但是,此代码无法正常运行。我希望打印出

国家表中的名称,资本,人口,描述 和 吸引人列表中的吸引力名称。

所以我期望的输出应如下所示:

  

{“国家”:法国,“首都”:巴黎,“人口”:64750000,“描述”:某些文字,“景点”:La Vieille Charite}

但是我的php现在输出什么: enter image description here

while循环有问题吗?还是有比UNION ALL更好的解决方案?

1 个答案:

答案 0 :(得分:0)

您真正想要的是LEFT JOIN。如果有没有景点的国家,请使用LEFT JOIN。试试这个:

$sql = "SELECT c.name, c.capital, c.population, c.description, a.attraction_name 
        FROM countries c
        LEFT JOIN attraction_list a ON a.country_name = c.name
        WHERE c.name ='France'";

如果一个国家/地区中有多个景点,则此查询将为您提供多行

{"country":France, "capital":Paris, "population": 64750000, "description":Some text, "attraction":La Vieille Charite},
{"country":France, "capital":Paris, "population": 64750000, "description":Some text, "attraction":Eiffel Tower}

如果您只想要一行,例如

{"country":France, "capital":Paris, "population": 64750000, "description":Some text, "attraction":La Vieille Charite, Eiffel Tower}

您可以使用GROUP BY进行汇总,例如

$sql = "SELECT c.name, c.capital, c.population, c.description, GROUP_CONCAT(a.attraction_name)
        FROM countries c
        LEFT JOIN attraction_list a ON a.country_name = c.name
        WHERE c.name ='France'
        GROUP BY c.name";