在返回的数据集中创建自定义值/列

时间:2012-12-09 07:43:40

标签: mysql union

我有一种情况,我正在使用这样的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);

现在,我想知道的是每个结果来自哪个表,所以我想知道我是否可以为每个返回的结果添加某种自定义结果,以便给我一些表明它来自哪个表格。

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

2 个答案:

答案 0 :(得分: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”),具体取决于行来自哪个联合的哪一侧

答案 1 :(得分: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);