【发布时间】:2020-01-14 13:44:27
【问题描述】:
我们有两个表credit_points 和debit_points,其中user_id 是参考。我们关心的是,我们希望通过 created_date DESC 获取具有限制和偏移量的单个查询顺序中的所有记录。请找到表格列表和输出表格。
credit_points
+----+----------+--------------+---------------------+
| id | user_id | credit_value | created_date |
+----+----------+--------------+---------------------+
| 1 | 111 | 13 | 2020-01-08 10:20:26 |
| 2 | 111 | 11 | 2020-01-09 11:20:23 |
| 3 | 111 | 7 | 2020-01-09 13:25:12 |
| 4 | 111 | 20 | 2020-01-13 12:25:17 |
+----+----------+--------------+---------------------+
debit_points
+----+----------+--------------+---------------------+
| id | user_id | debit_value | created_date |
+----+----------+--------------+---------------------+
| 1 | 111 | 13 | 2020-01-09 10:20:25 |
| 2 | 111 | 11 | 2020-01-11 11:18:54 |
| 3 | 111 | 15 | 2020-01-14 13:50:24 |
| 4 | 111 | 5 | 2020-01-14 15:23:12 |
+----+----------+------------+-----------------------+
输出应该是:
+----------+--------------+---+------------------------------+
| user_id | credit_value | debit_value | created_date |
+----------+--------------+-------------+--------------------+
| 111 | NULL | 5 |2020-01-14 15:23:12 |
| 111 | NULL | 15 |2020-01-14 13:50:24 |
| 111 | 20 | NULL |2020-01-13 12:25:17 |
| 111 | NULL | 11 |2020-01-11 11:18:54 |
| 111 | 7 | NULL |2020-01-09 13:25:12 |
| 111 | 11 | NULL |2020-01-09 11:20:23 |
| 111 | NULL | 13 |2020-01-09 10:20:25 |
| 111 | 13 | NULL |2020-01-08 10:20:26 |
+----------+--------------+-------------+-----+--------------+
查询1:
SELECT
c.user_id, c.credit_value, d.debit_value, d.created_date
FROM credit_points c
RIGHT JOIN debit_points d ON(c.user_id=d.user_id)
WHERE c.user_id=111
ORDER BY c.created_date,d.created_date DESC
limit 20;
我知道上面的查询是完全错误的。请帮助我以正确的方式获取它。
查询2:
SELECT user_id,credit_value, created_date
FROM credit_points where user_id=111
UNION ALL
SELECT user_id,debit_value,created_date
FROM debit_points where user_id=111 ORDER BY created_date DESC
上述查询(Query2)工作正常,但我们无法获取debit_value 列。 credit_value 和 debit_value 都在一个列中。
【问题讨论】:
-
RIGHT JOIN... 大多数人发现
main table left join optional data比optional data right join main table更容易理解。 -
看起来像 UNION ALL。
-
@jarlh 是的,UNION 提供了所有数据,但无法设置限制和偏移量。如果您知道,请分享有关此问题的完整查询
-
@jarlh 另外,我们如何按 created_date 降序排列?
-
将您的 UNION ALL 尝试添加到问题中,了解 MySQL 的人可能很快就会帮助您。