0

例子:

SELECT fbs_household_id,fbh_file_no, fbc_last_name,fbc_first_name
    FROM fbs_household
        LEFT JOIN (SELECT fbc_household_id, fbc_last_name,fbc_first_name FROM fbs_client WHERE fbc_household_id=fbs_household_id ORDER BY fbc_dob ASC LIMIT 1) t1 ON 1;

fbs_household_id来自fbs_household表格,但我收到一条错误消息,提示未知字段。

我可以将查询重写为:

SELECT fbs_household_id,fbh_file_no, fbc_last_name,fbc_first_name
    FROM fbs_household
        LEFT JOIN fbs_client ON fbs_client_id=(SELECT fbs_client_id
            FROM fbs_client
            WHERE fbc_household_id=fbs_household_id ORDER BY fbc_dob ASC LIMIT 1)

但这非常慢。有什么办法可以加快速度吗?

我正在尝试获取每个家庭中最年长的成员,以及有关该家庭的一些其他信息(实际查询包含更多列和连接)。


第三种解决方案,也很慢:

SELECT fbs_household_id,fbh_file_no, fbc_last_name,fbc_first_name
    FROM fbs_household
    LEFT JOIN (SELECT fbc_household_id, fbc_last_name,fbc_first_name
        FROM fbs_client
        ORDER BY fbc_dob ASC) c1 ON fbc_household_id=fbs_household_id;
4

2 回答 2

1

不确定这是否可行,但您是否尝试过子查询来获取max(fbc_dob)每个家庭的值,然后再次加入表以获取其他值:

SELECT h.fbs_household_id, h.fbh_file_no, c1.fbc_last_name, c1.fbc_first_name
FROM fbs_household h
LEFT JOIN fbs_client c1
  ON h.fbs_household_id = c1.fbc_household_id
LEFT JOIN
(
    select max(fbc_dob) fbc_dob, fbc_household_id  --- this will get you the oldest per household
    from fbs_client
    group by fbc_household_id
) c2
    ON c1.fbc_household_id = c2.fbc_household_id
    AND c1.fbc_dob = c2.fbc_dob

*不确定我是否将别名放置在选择中的正确字段上。

于 2012-11-20T19:23:47.207 回答
1

尝试通过将客户端表中的每一行与同一家庭的年长成员的行进行自联接,然后选择没有找到此类年长者的那一个,来找到每个家庭中最年长的客户。

SELECT fbs_household_id, fbh_file_no, c1.fbc_last_name, c1.fbc_first_name
FROM fbs_household
LEFT JOIN fbs_client c1 
ON c1.fbc_household_id = fbs_household_id 
LEFT JOIN fbs_client c2
ON c1.household_id = c2.household_id
AND (c1.dob > c2.dob
     OR c1.dob = c2.dob 
     AND c1.fbs_client_id > c2.fbs_client_id) -- if same dob, choose lower id
WHERE c2.dob IS NULL
于 2012-11-20T20:10:30.033 回答