php - 在这种情况下如何使用 UNION (MySQL)

标签 php mysql database

我在数据库中有两个表( table_1table_2 ),每个表都有一个名为 Name 的共同列.

我目前正在使用以下代码仅从 Name 导入一些数据( statustable_1 ) :

/* database section start */
    $mysqli = new mysqli("z","z","z","z");

    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
/* database section end */

// Choose Relevant items, and turn them into an array
$item_array = array(
'item1', 
'item2',
'item3'
);

//implode items, turn into string
$item_implode = join("','", $item_array);

//declare an overall array for result
$product = array();

$result = $mysqli->query("SELECT Name, Status as status from table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");

while($row = $result->fetch_assoc()) {

    $product_name = $row['Name'];
    // find all keys in $item_array which value is the products
        $keys = array_keys($item_array, $product_name);
    foreach ($keys as $key) {

        // add values for these keys
        $product[$key + 1]["Name"] = $row['Name'];
        $product[$key + 1]["status"] = $row['status'];//

    }
}

如果我想从 table_2 导入数据,我应该在这段代码中添加什么?以及(例如,名为 colordate_added 的列)?

我的目标是拥有这些 key :

$product[$x]["Name"]
$product[$x]["status"]
$product[$x]["color"]
$product[$x]["date_added"]

编辑:

这么长的帖子没有回答我的问题。该代码与我正在使用的代码不相似,我想知道如何在这个具体案例中准确应用 UNION。

我尝试过使用:

$result = $mysqli->query

("(SELECT Name, status as status from table_1 ) 

UNION

(SELECT Name, color as color from table_2 )

where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");


while($row = $result->fetch_assoc()) {

但是我在最后一行遇到 fatal error 。

编辑2:

仍然出现错误:

$result = $mysqli->query

("(SELECT Name, status as statu table_1 where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') ) 
UNION (SELECT color from table_2  where Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode') );");

while($row = $result->fetch_assoc()) {

最佳答案

$result = $mysqli->query("SELECT table_1.Name, table_1.Status,table_2.color,table_2.date_added from table_1 inner join table_2 on table_1.Name=table_2.Name where table_1.Name IN ('$item_implode') ORDER BY FIELD (Name, '$item_implode');");

关于php - 在这种情况下如何使用 UNION (MySQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38346611/

相关文章:

mysql - 如何mysql连接来自同一个表的两个选择查询结果

mysql - 显示订单总数以及订单号所售出的产品数量

R Studio 随机化日期和时间

java - 寻求一些了解 simpleCursorAdapter 工作原理的见解

php - SSL 连接错误 :140770FC

PHP 和 MySQL - fatal error : Function name must be a string

php - php手册中关键字 "Classes must be defined before they are used "如何理解 "extends"

php - 如何使用php计算父节点的所有子节点

php - MYSQL 多查询

php - 使用php中的输入字段将表行数据提交到另一个表