我有一个活动页面和每个用户的状态消息页面。
在活动中,它包含用户所做的事情,例如与某人成为朋友,对图片进行评论等等。
users_activities
id | uID | msg | date
在users_statusmessages中,我获得了用户创建的状态消息。
users_statuses
id | uID | message | date
uID是用户的身份。
现在我想同时选择它们和{}它们。它们按日期desc排序(因为两个表中的日期是UNIX时间戳)。
类似于WHERE uID = '$userID' ORDER BY date DESC
所以我希望它看起来如何:
User: Today is a good day (message) (date: 1284915827) (users_statuses)
User have added as Jack as friend (msg) (date: 1284915811) (users_activities)
User: I have a hard day today (message) (date: 1284915801) (users_statuses)
User have commented on Jacks picture (msg) (date: 1284915776) (users_activities)
我该如何以正确的方式做到这一点?
答案 0 :(得分:2)
您需要使用UNION运算符:
SELECT ua.msg,
ua.date,
'activity' AS is_table
FROM USERS_ACTIVITIES ua
WHERE ua.uid = '{$userID}'
UNION ALL
SELECT us.message,
us.date,
'status'
FROM USERS_STATUSES us
WHERE us.uid = '{$userID}'
ORDER BY `date`
UNION
删除重复项。 UNION ALL
不会删除重复项,并且速度更快。
但是SELECT中每个位置的数据类型必须匹配。在提供的查询中,您可以看到在第二个位置引用了日期列。如果第一个和第二个查询之间的列顺序相反,则会出现错误。
ORDER BY应用于标准SQL中UNION'd查询的结果。在MySQL中,包含LIMIT
子句。但MySQL也支持在UNION'd查询周围放置括号,以便您可以使用ORDER BY&在查询为UNION'd之前限制。
答案 1 :(得分:0)
你想要使用联盟
http://dev.mysql.com/doc/refman/5.0/en/union.html
这是未经测试的......
(SELECT uID, msg as message, date from users_activities)
UNION
(SELECT uId, message, date from users_statuses) order by date desc limit 20
该页面上有更多的例子
答案 2 :(得分:0)
这样的事情可以做到
SELECT act.*,status.* FROM users_activities act, users_statuses status WHERE act.id = status.id AND status.id = '$UID' ORDER BY status.date,act.date DESC LIMIT 30
出于视觉目的而间隔:
SELECT
act.*,status.*
FROM
users_activities act,
users_statuses status
WHERE
act.id = status.id
AND
status.id = '$UID'
ORDER BY
status.date,act.date DESC
LIMIT
30