对于约会应用程序,我有几个表需要查询单个输出,两个查询的 LIMIT 10 组合。目前似乎很难做到,即使单独查询它们不是问题,但 LIMIT 10 将不起作用,因为数字不准确(例如,不是 LIMIT 5 和 LIMIT 5,一个查询可能返回 0 行,而其他 10 个,视情况而定)。
members table
member_id | member_name
------------------------
1 Herb
2 Karen
3 Megan
dating_requests
request_id | member1 | member2 | request_time
----------------------------------------------------
1 1 2 2012-12-21 12:51:45
dating_alerts
alert_id | alerter_id | alertee_id | type | alert_time
-------------------------------------------------------
5 3 2 platonic 2012-12-21 10:25:32
dating_alerts_status
status_id | alert_id | alertee_id | viewed | viewed_time
-----------------------------------------------------------
4 5 2 0 0000-00-00 00:00:00
假设您是 Karen 并且刚刚登录,您应该会看到以下 2 项:
1. Herb requested a date with you.
2. Megan wants a platonic relationship with you.
在一个 LIMIT 为 10 的查询中。相反,这里有两个查询需要合并:
1. Herb requested a date with you.
-> query = "SELECT dr.request_id, dr.member1, dr.member2, m.member_name
FROM dating_requests dr
JOIN members m ON dr.member1=m.member_id
WHERE dr.member2=:loggedin_id
ORDER BY dr.request_time LIMIT 5";
2. Megan wants a platonic relationship with you.
-> query = "SELECT da.alert_id, da.alerter_id, da.alertee_id, da.type,
da.alert_time, m.member_name
FROM dating_alerts da
JOIN dating_alerts_status das ON da.alert_id=das.alert_id
AND da.alertee_id=das.alertee_id
JOIN members m ON da.alerter_id=m.member_id
WHERE da.alertee_id=:loggedin_id AND da.type='platonic'
AND das.viewed='0' AND das.viewed_time<da.alert_time
ORDER BY da.alert_time LIMIT 5";
同样,有时两个表都可能是空的,或者 1 个表可能是空的,或者都是满的(其中 LIMIT 10 开始)并按时间排序。关于如何获取查询以有效执行此任务的任何想法?欢迎提出想法、建议、提示、优化。