我有一个查询,从同一个数据库中的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 }
?>
答案 0 :(得分: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']; ?>
答案 1 :(得分: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代码以处理额外的列。
答案 2 :(得分:1)
select *, 'table_name'
如何作为字段,然后使用该列将它们发送到适当的位置。