我有一个带有多个连接的select语句,每个连接都有一个名为'created_on'的列名,是否有办法使查询的where部分检查所有3个表?这是我做的实际查询
SELECT *
FROM household_address
JOIN catchment_area ON catchment_area.household_id = household_address.household_id
JOIN bhw ON catchment_area.bhw_id = bhw.user_username
JOIN master_list ON master_list.person_id = catchment_area.person_id
JOIN house_visits ON house_visits.household_id = household_address.household_id
WHERE catchment_area.household_id IN (
SELECT household_address.household_id
FROM demo.household_address
JOIN catchment_area ON catchment_area.household_id = household_address.household_id
JOIN previous_cases ON catchment_area.person_id = previous_cases.person_id
JOIN active_cases ON catchment_area.person_id = active_cases.person_id
JOIN ls_report ON ls_report.ls_household = household_address.household_name
WHERE DATE(created_on) BETWEEN '2014-03-01' AND '2014-03-31'
)
我正在谈论的连接是子查询中的连接。
答案 0 :(得分:5)
首先,您应该为每个表名创建一个别名,以便更容易阅读和更快地编写..
SELECT *
FROM household_address AS ha
JOIN catchment_area ca ON ca.household_id = ha.household_id
JOIN bhw bh ON ca.bhw_id = bh.user_username
JOIN master_list ml ON ml.person_id = ca.person_id
JOIN house_visits hv ON hv.household_id = ha.household_id
WHERE ca.household_id IN
(
SELECT ha1.household_id
FROM demo.household_address AS ha1
JOIN ca1 ON ca1.household_id = ha1.household_id
JOIN previous_cases pc ON ca1.person_id = pc.person_id
JOIN active_cases ac ON ca1.person_id = ac.person_id
JOIN ls_report ls_r ON ls_r.ls_household = ha1.household_name
WHERE DATE(ha1.created_on) BETWEEN '2014-03-01' AND '2014-03-31'
AND DATE(ca1.created_on) BETWEEN '2014-03-01' AND '2014-03-31'
AND DATE(pc.created_on) BETWEEN '2014-03-01' AND '2014-03-31'
AND DATE(ac.created_on) BETWEEN '2014-03-01' AND '2014-03-31'
AND DATE(ls_r.created_on) BETWEEN '2014-03-01' AND '2014-03-31'
)
对于每个创建日期的条件,你必须告诉它WHERE(table_name.created_on BETWEEN .....)
为每个表执行此操作
答案 1 :(得分:1)
尝试使用带有其他WHERE子句的别名。
SELECT
*
FROM household_address
JOIN catchment_area ON catchment_area.household_id = household_address.household_id
JOIN bhw ON catchment_area.bhw_id = bhw.user_username
JOIN master_list ON master_list.person_id = catchment_area.person_id
JOIN house_visits ON house_visits.household_id = household_address.household_id
WHERE catchment_area.household_id IN (
SELECT household_address.household_id
FROM demo.household_address ha
JOIN catchment_area ca ON ca.household_id = ha.household_id
JOIN previous_cases pc ON ca.person_id = pc.person_id
JOIN active_cases ac ON ca.person_id = ac.person_id
JOIN ls_report ls_r ON ls_r.ls_household = ha.household_name
WHERE DATE(ha.created_on) BETWEEN '2014-03-01' AND '2014-03-31'
AND DATE(ca.created_on) BETWEEN '2014-03-01' AND '2014-03-31'
AND DATE(pc.created_on) BETWEEN '2014-03-01' AND '2014-03-31'
)
我实际上并不知道哪三个表都有'created_on'字段,所以我选择了household_address,catchment_area和previous_cases作为示例。将这些更改为您实际想要搜索的内容。
(也可能应该是所有表名的别名)