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

时间:2016-07-13 08:38:17

标签: 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的列),我应该向此代码添加什么内容?

我的目标是拥有这些钥匙:

$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()) {

但是我在最后一行遇到致命错误。

EDIT2:

仍然出错:

$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()) {

4 个答案:

答案 0 :(得分:1)

$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');");

答案 1 :(得分:1)

(SELECT Name, Status as status FROM table_1 t1)
UNION
(SELECT color, date_added FROM table_2 t2)

答案 2 :(得分:0)

更改您的查询,并尝试使用:INNER JOIN table_2

我无法为您查询,因为我没有您的数据......

答案 3 :(得分:0)

使用联接构建查询。

$query="SELECT t1.Name, t1.Status as status, t2.color, t2.date_added) from "
  ."table_1 t1 "
  ."LEFT JOIN table_2 t2 ON t2.Name "
  ."where t1.Name IN ('$item_implode') "
  ."AND t2.Name = t1.Name "
  ."ORDER BY FIELD (t1.Name, '$item_implode');";