如何从SQL查询合并两个数组?

时间:2013-07-22 10:35:12

标签: php sql arrays associative-array array-merge

我有两个问题:

SELECT date( FROM_UNIXTIME( user_reg_date ) ) 'Current Date', COUNT( * ) 'registered_user'
FROM users
WHERE user_reg_date >=1341100800
AND user_reg_date <=1374451200
GROUP BY date( FROM_UNIXTIME( user_reg_date ) )

SELECT date( FROM_UNIXTIME( user_last_login ) ) 'Current Date', COUNT( * ) 'logged_in_user'
FROM users
WHERE user_last_login >=1341100800
AND user_last_login <=1374451200
GROUP BY date( FROM_UNIXTIME( user_last_login ) )

现在我想合并我从上面的查询得到的两个数组,每个数组元素应该是以下形式。

date = > array(registered_user, logged_in_user)

在这方面有谁能帮助我?提前谢谢。

2 个答案:

答案 0 :(得分:2)

使用UNION之类的

SELECT date( FROM_UNIXTIME( user_reg_date ) ) 'Current Date', COUNT( * ) 'registered_user'
FROM users
WHERE user_reg_date >=1341100800
AND user_reg_date <=1374451200
GROUP BY date( FROM_UNIXTIME( user_reg_date ) )

UNION

SELECT date( FROM_UNIXTIME( user_last_login ) ) 'Current Date', COUNT( * )   'logged_in_user'
FROM users
WHERE user_last_login >=1341100800
AND user_last_login <=1374451200
GROUP BY date( FROM_UNIXTIME( user_last_login ) )

但请注意这两个表所具有的重复列。尝试使用像

这样的表对象来调用它们
table1.id,table2.id

考虑两个表中都存在id

答案 1 :(得分:1)

您可以执行一个非常简单的UNION ALL,并按日期分组SUM以获取值;

SELECT DATE(FROM_UNIXTIME(date)) date, 
       SUM(registered_user) registered_user, 
       SUM(logged_in_user) logged_in_user
FROM (
  SELECT user_reg_date date, 1 registered_user, 0 logged_in_user FROM users
  UNION ALL
  SELECT user_last_login,    0 registered_user, 1 logged_in_user FROM users
) a
WHERE date >= 1341100800 AND date <= 1374451200
GROUP BY DATE(FROM_UNIXTIME(date));