我有这样的查询
SELECT hc_num,client_pow,client_id,date_issued,client_occup
FROM tbl_health_certificate t1
WHERE date_issued =
(SELECT MAX(date_issued)
FROM tbl_health_certificate t2
WHERE t2.client_id=t1.client_id) AND year(date_issued) < year(now())
现在我希望将结果连接到另一个表,以获取某些行值,尤其是client_fname
和client_lname
字段。我该怎么做? :)
我的表格结构如下 - &gt; tbl_health_certificate,[tbl_client] [2]
Content of tbl_health_certificate
应显示的结果是带有client_id的行: -26 -29
使用表tbl_client
中的client_fname和client_lname答案 0 :(得分:0)
好吧,经过一夜的睡眠,我明白为什么我昨天的答案不起作用。我认为子查询是不必要的,但我错了,因为聚合列中的值不一定来自与MAX(tbl_health_certificate.date_issued)
相同的行。此外,我困倦的头脑没有意识到WHERE
在分组发生之前缩小了结果,所以这确实会导致来自今年最近一行的客户的行显示出来。 “不是来自今年”的条件应该放在HAVING
条款中,正如我在下面所做的那样。
此查询的嵌套级别低于OP自己的解决方案,因此我认为这是一个很好的选择。
SELECT t1.hc_num, t1.client_pow, t1.client_id,
t1.date_issued, t1.client_occup, t4.client_fname, t4.client_lname
FROM tbl_health_certificate t1
JOIN
(SELECT t2.client_id, MAX(t2.date_issued) AS max_date
FROM tbl_health_certificate t2
GROUP BY t2.client_id
HAVING year(MAX(t2.date_issued)) < year(now())) t3
ON t1.client_id = t3.client_id AND t1.date_issued = t3.max_date
JOIN tbl_client t4 ON t1.client_id = t4.client_id
答案 1 :(得分:0)
修改了几行。
select table1.* , table2.* from
(SELECT hc_num,client_pow,client_id,date_issued,client_occup
FROM tbl_health_certificate t1,
(SELECT MAX(date_issued) date_issued_max
FROM tbl_health_certificate t2 group by client_id) t2
WHERE t1.date_issued = t2.date_issued_max
AND year(date_issued) < year(now())) table1
left/right/full outer join -- use appropriate join
tbl_client table2 ON table1.client_id = table2.client_id
答案 2 :(得分:0)
我相信查询会是这样的:
SELECT
t2.client_fname, t2.client_lname, t1.hc_num, t1.client_pow,
t1.client_id, MAX(t1.date_issued) as 'date_issued', t1.client_occup
FROM tbl_health_certificate t1 INNER JOIN
tbl_client t2 ON t2.client_id = t1.client_id
WHERE year(t1.date_issued) < year(now())
GROUP BY t1.client_id
带有GROUP BY的MAX会有所帮助,然后t1的任何行结果会立即加入tbl_client以检索客户端信息。