我有一個DB(table_1
和table_2
)兩個表使用UNION,他們每個人都有所謂Name
相互列。我目前使用下面的代碼輸入一些數據(Name
,status
)只能從table_1
如何在這種情況下(MySQL的)
:
/* 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
導入數據,以及我應該添加到這個代碼(例如,列名爲color
,date_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()) {
使用'UNION'(http://dev.mysql.com/doc/refman/5.7/en/union.html) – rokas