我在一个数据库中有多个表,每个表都包含完全相同的列名。我使用 SQL UNION 来从所有这些表中提取每条记录,并将记录输出到网页上。每条记录都在 ID 为“contributors”的 div 之间输出。
我最终要做的是在正在输出的每个表之间设置某种分隔,这样我就不会让表中的每个记录无缝地运行到下一个表中。
我尝试在“贡献者”div 之前回显一个 div,但这不起作用。有谁知道如何从问题 1 输出数据,然后创建一个标题到下面以将问题 1 与问题 2 分开?
<?php
$res=mysql_query('
SELECT First, Last, Title, StoryLink, Genre, About, Link, Picture, ALT FROM issue1 UNION ALL
SELECT First, Last, Title, StoryLink, Genre, About, Link, Picture, ALT FROM issue2 UNION ALL
SELECT First, Last, Title, StoryLink, Genre, About, Link, Picture, ALT FROM issue3
');
if (!$res) { // add this check.
die('Invalid query: ' . mysql_error());
}
while($row=mysql_fetch_array($res))
{
$cont_img_path = $img_path.end(explode('/', $row['Picture']));
if(file_exists($cont_img_path))
{
?>
<div class="contributors">
<h6><?php echo $row['First']; ?> <?php echo $row['Last']; ?></h6>
<h2 style="color:#ffffff;"><em><?php echo $row['Title']; ?></em></h2>
<p style="color:#ffd997;"><?php echo $row['Genre']; ?></p>
<h3 class="ctr-image"><a href="<?php echo $row['Picture']; ?>" id="3e-fancybox" name="<?php echo $row['First'] .' '. $row['Last']; ?>" StoryLink="<?php echo $row['StoryLink']; ?>" Ptitle="<?php echo $row['Title']; ?>" genre="<?php echo $row['Genre']; ?>" about="<?php echo str_replace('"', '"', ($row['About'])); ?>" WebLink="<?php echo $row['Link']; ?>"><img src="<?php echo $row['Picture']; ?>" alt="<?php echo $row['ALT']; ?>"></a></h3>
</div>
<?php } } ?>
最佳答案
尽管如此,如果您想要三个单独的结果集,那么使用 AJAX 并发出三个单独的请求更有意义,这里有一个解决方案:
$res = mysql_query('
SELECT
'Issue1' as context,
First,
Last,
Title,
StoryLink,
Genre,
About,
Link,
Picture,
ALT
FROM
issue1
UNION ALL
SELECT
'Issue2' as context,
First,
Last,
Title,
StoryLink,
Genre,
About,
Link,
Picture,
ALT
FROM
issue2
UNION ALL
SELECT
'Issue3' as context,
First,
Last,
Title,
StoryLink,
Genre,
About,
Link,
Picture,
ALT
FROM
issue3
)';
这解决了问题,但我不相信您的数据库结构一开始就是正确的。
关于php - 如何使用 SQL UNION 分离 SQL 表的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36346637/