2

我有一种情况,我正在使用这样的 UNION:

$query = "SELECT bigimage, heading, fullarticle, dateadded FROM news ";
$query .= "WHERE (state = '" . $USER->state . "' OR state = 'ALL') AND status = 1 AND newstype != 1 AND frontpage = 1 AND bigimage > '' ";
$query .= "UNION ";
$query .= "SELECT image, eventname, details, dateadded FROM events ";
$query .= "WHERE (state = '" . $USER->state . "' OR state = 'ALL') AND status = 1 AND frontpage = 1 AND image > '' ";
$query .= "ORDER BY dateadded DESC LIMIT 10";
$restresult = mysql_query($query);

现在,我想知道每个结果来自哪个表,所以我想知道是否可以为返回的每个结果添加某种自定义结果,以某种形式指示它来自哪个表。

我可以在返回的结果中以某种方式添加一个额外的“动态”列吗?

4

2 回答 2

2

当然。去掉不相关的 php 代码,您的查询可能是:

SELECT 'news' as type, bigimage, heading, fullarticle, dateadded FROM news
WHERE (state = ? OR state = 'ALL') AND status = 1 AND newstype != 1 AND frontpage = 1 AND bigimage > ''
UNION
SELECT 'event', image, eventname, details, dateadded FROM events 
WHERE (state = ? OR state = 'ALL') AND status = 1 AND frontpage = 1 AND image > ''
ORDER BY dateadded DESC 
LIMIT 10

这只是添加了一个具有不同值的常量列(我称为“type”)(我在从中选择行的表之后使用了“news”和“event”),具体取决于该行来自联合的哪一侧。

于 2012-12-09T07:49:10.753 回答
2

试试这个:

$query = "SELECT bigimage, heading, fullarticle, dateadded, 'news' as TableName FROM news ";
$query .= "WHERE (state = '" . $USER->state . "' OR state = 'ALL') AND status = 1 AND newstype != 1 AND frontpage = 1 AND bigimage > '' ";
$query .= "UNION ";
$query .= "SELECT image, eventname, details, dateadded, 'event' FROM events ";
$query .= "WHERE (state = '" . $USER->state . "' OR state = 'ALL') AND status = 1 AND frontpage = 1 AND image > '' ";
$query .= "ORDER BY dateadded DESC LIMIT 10";
$restresult = mysql_query($query);
于 2012-12-09T07:51:23.083 回答