问题描述
我有 2 个表:users &平衡.
I have 2 tables: users & balance.
我想将包含来自用户表(所有元组的所有字段)的所有详细信息的表与余额表中的最新条目(由用户 ID 链接的 1 个字段)连接起来.
I want to join the tables with all of the details from the user table (all fields of all tuples) with the most recent entry from the balance table (1 field linked by a user id).
表的结构如下:
余额:
+---------+
| Field |
+---------+
| dbid |
| userId |
| date |
| balance |
+---------+
用户:
+-------------+
| Field |
+-------------+
| dbid |
| id |
| fName |
| sName |
| schedName |
| flexiLeave |
| clockStatus |
+-------------+
我已经尝试了几个小时来做到这一点,我能得到的最接近的是为单个用户返回一行:
I have been trying for hours to do this and the closest I can get is to return a row for a single user:
SELECT u.*, b.balance, b.date
FROM users u, balance b
WHERE
u.id = b.userId AND
b.date = (SELECT MAX(date) FROM balance WHERE userId = 'A8126982');
或者我可以选择所有用户但不选择余额表中的最新条目:
Or I can select all users but not the most recent entry in the balance table:
SELECT u.*, b.balance, b.date
FROM users u, balance b
WHERE u.id = b.userId GROUP BY u.id;
我尝试了许多不同的查询,似乎越来越接近,但我就是无法到达我想去的地方.
I have tried many different queries and seem to be getting closer but I just can't get to where I want to be.
任何帮助将不胜感激.
推荐答案
您可以使用您编写的第一个 SQL,但适用于所有用户:
You can use the first SQL you wrote but for all users:
SELECT u.*, b.balance, b.date
FROM users u JOIN balance b ON u.id = b.userId
WHERE b.date = (SELECT MAX(date) FROM balance WHERE userId = u.id);
这可能不是获得结果的最快方法,但它会为您提供所需的信息.我在应用中的很多地方都使用了类似的查询.
This may not be the fastest way to get the result, but it'll give you what you need. I use similar queries in quite a few places in my app.
这篇关于MySQL - 加入 2 个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)