1

我有一个查询从同一数据库中的 3 个 SQL 表中随机选择 6 个图像,一旦有人单击该图像,我想根据从哪个表中选择该图像将它们发送到单独的页面。为此,我想通过查询找出选择了该随机图像的表名。

我的 SQL 查询是

$sql="SELECT *
FROM   salehotel
UNION ALL
SELECT *
FROM   saleland
UNION ALL
SELECT *
FROM   salehouse
ORDER BY RAND()
LIMIT 6
";
$result=mysql_query($sql)or die(mysql_error());
?>
<?php
        while($row = mysql_fetch_array($result))
        {?>
    <div style="float: left; margin-left: 10px;">
        <a href="sale_house_detail.php?id=<?php echo $row['property_id'];  ?>">
            <img src=<?= '"admin/uploads/'.$row['image1'].'"'; ?> width="172px" height="149px" style='border:5px solid  #CCC' />
        </a>
    <p><?php  echo $row['Type']; ?></p>
    <p><?php  echo $row['Location']; ?></p>
  </div>

    <?php   }
    ?>
4

3 回答 3

3

在 SQL 中创建一个指示源表的新字段:

$sql="SELECT salehotel.*, 'salehotel' as source
FROM   salehotel
UNION ALL
SELECT saleland.*, 'saleland' as source
FROM   saleland
UNION ALL
SELECT salehouse.*, 'salehouse' as source
FROM   salehouse
ORDER BY RAND()
LIMIT 6
";

然后,您的 PHP 可以将此列显示为:

<?php  echo $row['source']; ?>
于 2012-09-22T14:48:59.553 回答
1

在查询中包含表名:

SELECT 'salehotel' as which, sh.*
FROM   salehotel sh
UNION ALL
SELECT 'saleland' as which, sl.*
FROM   saleland sl
UNION ALL
SELECT 'salehouse' as which, sho.*
FROM   salehouse sho
ORDER BY RAND()
LIMIT 6

然后适当地更改 php 代码以处理额外的列。

于 2012-09-22T14:48:51.587 回答
1

怎么样select *, 'table_name'作为一个字段,然后使用该列将它们发送到适当的位置。

于 2012-09-22T14:50:23.230 回答