需要一些sql帮助...使用MYSQL ...我有一些遗留代码和要解决的情况......下面这段代码只返回在p_occupants_insurance表中有记录的占用者。我希望能够列出所有占用者,无论他们是否在p_occupants_insurance表中有记录。
SELECT a.occupants_insurance_id, a.occupant_id, a.policy_nbr, a.policy_type, a.coverage_amount_curr,
CASE
WHEN a.effective_date = '0000-00-00' THEN NULL
ELSE a.effective_date
END as effective_date,
CASE
WHEN a.expiration_date = '0000-00-00' THEN NULL
ELSE a.expiration_date
END as expiration_date,
a.insurance_company, a.custom1_label, a.custom2_label, a.custom3_label, a.custom1, a.custom2, a.custom3, c.name as prop_name, (SELECT x.name FROM portfolio_hierarchy x WHERE x.leaf_node_portf_id = d.portfolio_id ) as p_name, b.name as occupant_name, b.primary_contact, b.phone
FROM p_occupants_insurance a, p_occupants b, properties c, portfolio d
WHERE a.occupant_id = b.occupant_id
AND b.property_id = c.properties_id
AND c.portfolio_id = d.portfolio_id
AND d.account_id = 1
AND b.archived = 0
AND b.trashbin = 0
ORDER BY d.p_name ASC, prop_name ASC, occupant_name ASC, insurance_company ASC, policy_nbr ASC;
我知道我可以做这样的子查询:
SELECT b.name as occupant_name, b.primary_contact, b.phone,
(SELECT a.occupants_insurance_id FROM p_occupants_insurance a WHERE a.occupants_id = b.occupants_id) as occupants_insurance_id
FROM p_occupants b, properties c, portfolio d
WHERE a.occupant_id = b.occupant_id
AND b.property_id = c.properties_id
AND c.portfolio_id = d.portfolio_id
AND d.account_id = 1
AND b.archived = 0
AND b.trashbin = 0
ORDER BY d.p_name ASC, prop_name ASC, occupant_name ASC, insurance_company ASC, policy_nbr ASC;
但是这将导致我想要从p_occupants_insurance表中的每一列的子查询。有没有更好的方法来实现这一点,你能帮我写出SQL吗?对不起,SQL不是我的最强点。
感谢您的帮助。
答案 0 :(得分:2)
如果没有看到所涉及的每个表的模式,并且仅依赖于示例SQL语句,则很难确定,但我相信以下内容将返回您要查找的结果:
SELECT
a.`occupants_insurance_id`,
a.`occupant_id`,
a.`policy_nbr`,
a.`policy_type`,
a.`coverage_amount_curr`,
IF(a.`effective_date` = '0000-00-00',NULL,a.`effective_date`) as a.`effective_date`,
IF(a.`expiration_date` = '0000-00-00',NULL,a.`expiration_date`) as a.`expiration_date`,
a.`insurance_company`,
a.`custom1_label`,
a.`custom2_label`,
a.`custom3_label`,
a.`custom1`,
a.`custom2`,
a.`custom3`,
c.`name` as `prop_name`,
(SELECT x.name FROM portfolio_hierarchy x WHERE x.leaf_node_portf_id = d.portfolio_id ) as `p_name`,
b.`name` as `occupant_name`,
b.`primary_contact`,
b.`phone`
FROM `p_occupants` b
LEFT JOIN `p_occupants_insurance` a
ON a.`occupant_id` = b.`occupant_id`
JOIN `properties` c
ON b.`property_id` = c.`properties_id`
JOIN `portfolio` d
ON c.`portfolio_id` = d.`portfolio_id`
WHERE d.account_id = 1
AND b.archived = 0
AND b.trashbin = 0
ORDER BY d.p_name ASC,
`prop_name` ASC,
`occupant_name` ASC,
`insurance_company` ASC,
`policy_nbr` ASC;