以下查询有效,但由于某种原因,第一个select语句是唯一显示的URL。显示其他表中的项目,但是它们的URL错误。
$sql = "(SELECT postsID as postsID, postsSubject AS postsSubject, postsTimestamp AS timestamp
FROM posts
WHERE postsCategory = '$id')
UNION
(SELECT eventID as eventID, eventTitle as eventTitle, eventsTimestamp as timestamp
FROM events
WHERE eventLocation = '$id')
ORDER BY timestamp DESC";
从事件和帖子表中正确显示信息,但结果只显示在帖子表中。
例如,说我有以下信息
postsID | postsSubject | postsTimestamp
1 post 123
eventID | eventTitle | eventsTimestamp
2 event 456
我有以下内容来显示我的结果
while($row = mysql_fetch_assoc($result)){
?>
<tr><td><? echo '<a href="viewevent.php?eventID=' . $row['eventID'] . '">' . $row['eventTitle'] . '</a>' ; ?></td>
<tr><td><? echo '<a href="viewpost.php?postID=' . $row['postsID'] . '">' . $row['postsSubject'] . '</a>' ; ?></td>
<?
if(preg_match('/[0-9]/',$row['timestamp'])){
list($yyyy,$dd,$mm) = explode('-',$row['timestamp']);
$newDate = $dd."-".$mm."-".$yyyy;
}
?>
<td><center><? echo $newDate; ?></center></td></tr>
<?
}
echo '</table>';
}
输出似乎正确
post 123
event 456
但是,两个结果都链接到以下(分别)
viewpost.php?id = 1
viewpost.php?id = 2 //this should be viewevent.php
答案 0 :(得分:2)
sql如下:
$sql = "(SELECT postsID as ids, postsSubject AS description, postsTimestamp AS timestamp,'p' as status
FROM posts
WHERE postsCategory = '$id')
UNION
(SELECT eventID as ids, eventTitle as description, eventsTimestamp as timestamp, 'e' as status
FROM events
WHERE eventLocation = '$id')
ORDER BY timestamp DESC";
检索数据时,
while($row = mysql_fetch_assoc($result)){
if ($row['status']=="e"){
?>
<tr><td><? echo '<a href="viewevent.php?eventID=' . $row['ids'] . '">' . $row['description'] . '</a>' ; ?></td>
<? }else{?>
<tr><td><? echo '<a href="viewpost.php?postID=' . $row['ids'] . '">' . $row['description'] . '</a>' ; ?></td>
<? } ?>
<?
if(preg_match('/[0-9]/',$row['timestamp'])){
list($yyyy,$dd,$mm) = explode('-',$row['timestamp']);
$newDate = $dd."-".$mm."-".$yyyy;
}
?>
<td><center><? echo $newDate; ?></center></td></tr>
<?
}
echo '</table>';
}
答案 1 :(得分:0)
union / union都使用第一个表中的列将行放在一个表中。因此,结果集有一个PostsId,但没有EventsId。
也许您想要一个连接,它会将列并排放置。也许您希望将其作为两个单独的查询来运行。
以下是示例:
$sql = "select *
from (SELECT postsID as postsID, postsSubject AS postsSubject, postsTimestamp AS timestamp
FROM posts
WHERE postsCategory = '$id') p
cross join
(SELECT eventID as eventID, eventTitle as eventTitle, eventsTimestamp as timestamp
FROM events
WHERE eventLocation = '$id') e
ORDER BY postsTimeStamp DESC"
请注意,这是生产笛卡尔积。因此,如果其中一个表中有更多行,那么您将获得大量行。