在UNION中选择列

时间:2010-09-19 18:53:24

标签: php sql mysql union

$queryActivities = mysql_query("
SELECT ua.status, ua.date, 'status' AS is_table FROM users_statuslog ua
   WHERE ua.uid = '{$showU[id]}'
UNION ALL 
SELECT us.message, us.date 'wall' FROM users_wall us 
   WHERE us.uid = '{$showU[id]}'
ORDER BY `date` DESC");

这就是我现在所拥有的。而且我需要来自users_wall的更多列,比在users_statuslog中需要的更多。我该如何选择它们?因为我不能这样做:

(假设我也想要isReplyFrom并从users_wall查看)

$queryActivities = mysql_query("
SELECT ua.status, ua.date, 'status' AS is_table FROM users_statuslog ua
   WHERE ua.uid = '{$showU[id]}'
UNION ALL 
SELECT us.message, us.date, us.isReplyFrom, us.viewed 'wall' FROM users_wall us 
   WHERE us.uid = '{$showU[id]}'
ORDER BY `date` DESC");

我得到了:

使用的SELECT语句具有不同的列数。

3 个答案:

答案 0 :(得分:2)

如消息所示,您有两个选择,列数不同。
联合会将第一个选择的结果“连接”到第二个选择,但如果列数不相同则无法工作。

要么找到一种方法来拥有相同数量的列,要么在您的请求中添加虚拟列:

SELECT ua.status, ua.date, 'dummy' AS replyFrom, 'dummy' AS viewed, 'status' AS is_table FROM users_statuslog ua
    WHERE ua.uid = '{$showU[id]}'
UNION ALL
SELECT us.message, us.date, us.isReplyFrom, us.viewed, 'wall' FROM users_wall us 
    WHERE us.uid = '{$showU[id]}'
ORDER BY `date` DESC

资源:

答案 1 :(得分:1)

您需要在首次查询中添加一些假列

$queryActivities = mysql_query("
SELECT ua.status, ua.date, null AS isReplyFrom, null AS viewed, 'status' AS is_table FROM users_statuslog ua
   WHERE ua.uid = '{$showU[id]}'
UNION ALL 
SELECT us.message, us.date, us.isReplyFrom, us.viewed, 'wall' FROM users_wall us 
   WHERE us.uid = '{$showU[id]}'
ORDER BY `date` DESC");

答案 2 :(得分:1)

使用SELECT时,UNION语句的列数不能相同。您可能希望添加常量字段来代替额外列。也许是这样的:

SELECT ua.status, ua.date, 0 AS isReplyFrom, 'status' AS is_table 
FROM   users_statuslog ua
WHERE ua.uid = '{$showU[id]}'
UNION ALL 
SELECT us.message, us.date, us.isReplyFrom, us.viewed 'wall' 
FROM users_wall us 
WHERE us.uid = '{$showU[id]}'
ORDER BY `date` DESC