php - MYSQL、PHP)使用 UNION ALL 从多个表的所有列获取值

标签 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);
        }
    }

但是,这段代码并没有按照我的预期工作。我期望打印出来

国家表中的名称、首都、人口、描述 和 吸引点_列表中的吸引点名称。

所以我期望的输出应该是这样的:

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

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

是while循环的问题吗?或者也许有比 UNION ALL 更好的解决方案?

最佳答案

您真正想要的是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";

关于php - MYSQL、PHP)使用 UNION ALL 从多个表的所有列获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52683004/

相关文章:

php - 使用 mcrypt 或 GnuPG 存储信用卡详细信息

php - Yii2 中的自定义身份验证问题

mysql - 我需要多表查询中的空字段

mysql - 在 MySQL 中如何查询 1 行中的 2 列?

mysql - 如何在 MySQL 中连接整个结果集?

sql - 如何用SQL UNION指定订单结果?

php 和 mysql 函数滚雪球结果

php - 我需要一个 RegExp 来只匹配拉丁字符而不匹配其他字符

mysql - 从今天起,无法再通过 XAMPP 连接到本地 MY SQL 数据库 (mysqli_real_connect() : (HY000/2002))

php - Laravel hasMany 关系选择特定列问题