工會

2014-03-05 74 views
0

我將如何分辨其中一條記錄從下面的例子聯合查詢來區分內兩個查詢:工會

SELECT id, name, datetime FROM events 
UNION 
SELECT id, name, datetime FROM festival 
ORDER BY datetime DESC 

我使用它在PHP的方式是:

$stmt = $cxn->prepare('SELECT id, name, datetime FROM events WHERE id = ? UNION SELECT id, name, datetime FROM festival WHERE id = ? ORDER BY datetime DESC'); 
$stmt->bind_param('i', $event_id); 
$stmt->execute(); 
$stmt->store_result(); 
$stmt->bind_result($id, $name, $datetime); 

while ($stmt->fetch()) { 
    echo "ID: " . $id . "\n"; 
    echo "Name: " . $name . "\n"; 
    echo "Date: " . $datetime; 
} 

$stmt->close(); 

請幫我一把。

謝謝。

回答

1
SELECT id, name, datetime, 'events' FROM events 
UNION 
SELECT id, name, datetime, 'festival' FROM festival 
ORDER BY datetime DESC 

PHP

$stmt = $cxn->prepare('SELECT id, name, datetime, "events" as tablename FROM events WHERE id = ? UNION SELECT id, name, datetime, "festival" as tablename FROM festival WHERE id = ? ORDER BY datetime DESC'); 
$stmt->bind_param('i', $event_id); 
$stmt->execute(); 
$stmt->store_result(); 
$stmt->bind_result($id, $name, $datetime, $table); 

while ($stmt->fetch()) { 
    echo "ID: " . $id . "\n"; 
    echo "Name: " . $name . "\n"; 
    echo "Date: " . $datetime; 
    echo "Which Table: " . $table; 
} 

$stmt->close(); 
+0

我如何以PHP的方式獲取該列,因爲我的綁定結果是? – Walter

+0

@Aquillo糾正 – SajithNair

+0

一個改進是使用'UNION ALL',因爲這些記錄不再匹配了 – Aquillo

0

,你可以通過添加一個多列做到這一點,區分它想:如果

SELECT id, name, datetime, 'E' as fromwhere FROM events 
UNION 
SELECT id, name, datetime,'F' as fromwhere FROM festival 
ORDER BY datetime DESC 

fromwhere欄會告訴你從事件或節日它。

+0

我將如何得到我有它在PHP建立因爲我結合結果的方式'fromwhere'列? – Walter

+0

是不是可以在php中查詢本身添加?像這樣SELECT id,name,datetime,'E'FROM events WHERE id =? UNION SELECT id,name,datetime,'F'FROM festival WHERE id =? ORDER BY datetime DESC' –