UNION查询问题

时间:2013-01-02 07:02:58

标签: php mysql arrays content-management-system union

我正在尝试对我的数据库中的两个表进行简单的联合查询,尽管我无法检索成功的数组结果。应该注意的是,每个表都有不同的列,我想创建一个虚拟结果(促销AS来源[从'venpromo'表中拉出的结果]和&& vacation AS origin [for result from 'vacation'表])以便将结果排序到不同的数组结构中。我到处寻找,UNIONS都使用不同的语法。提前谢谢大家!

<?php
    require_once('includes/config.php');

    $event_query = "SELECT *, promo AS origin FROM venpromo
    UNION 
    SELECT *, vacation AS origin FROM venpromo 
    ORDER BY popularity DESC";
    $event_result = mysql_query($event_query, $connection);
    while ($event = mysql_fetch_array($event_result)) {
        if ($event['origin'] == "promo") {
            $event_array[] = array(
                'id' => $event['id'],
                'title' => $event['calname'],
                'start' => $event['sdate'],
                'end' => $event['edate'],
                'color' => "red",
                'url' => "http://www.norrisportal.com/bulletinpost.php?id=" . $event['id'] . "&hashkey=akdULjsjyUpYyTzOT7"
            );
        } elseif ($event['origin'] == "vacation") {
            $event_array[] = array(
                'id' => $event['id'],
                'title' => $event['reason'],
                'start' => $event['vacstart'],
                'end' => $event['vacend'],
                'color' => "blue"
            );
        }
    }

    echo json_encode($event_array);

?>

访问页面查看结果时,我看到'null'。

1 个答案:

答案 0 :(得分:2)

明确列出列名而不是*,并确保每个选择中相同列的列数和数据类型匹配。

我添加了一些虚拟列以匹配两个表中的数字和数据类型,并且还更改了列的顺序。

尝试这种样本方式::

select 
id,
uid,
approval,
vacstart,
vacend,
reason,
'dummy1' col1,
'dummy2' col2,
'dummy3' col3,
curdate() col4,
'dummy4' col5,
'dummy5' col6,
'dummy6' col7,
'dummy7' col8,
promo AS origin
from vacation
union
select
id,
venid,
authid,
sdate,
edate,
authname,
tags,
title,
calname,
date,
intro,
body,
sum,
sortdate,
vacation AS origin
from venpromo;