这是我的情景
所以,现在我想检查属于具有指定名称和指定区域的特定官员的信息是否已经在表中。
我是这样尝试的
SELECT DISTRICT_ID FROM DISTRICT WHERE DISTRICT_ID='(SELECT DISTRICT_ID FROM CITY WHERE CITY_ID='(SELECT CITY_ID FROM CITY_INFO WHERE CITY_PIN=(SELECT CITY_PIN FROM STATION_HOUSE WHERE STATION_ID='(SELECT STATION_ID FROM OFFICER_HISTORY OH,OFFICER O WHERE OH.OFFICER_ID=O.OFFICER_ID AND (O.DESIGN_ID='"+design+"' AND O.STATUS_TYPE='ACTIVE'))'))')' AND ZONE_ID='"+zone+"'
这意味着,它将显示状态为 ACTIVE 且属于指定区域的特定官员的区域ID。
如果上述查询返回信息,则表示信息已存在。因为,我的表中没有与条件相关的数据,但我认为我的SQL查询是完美的。但是,它太冗长了。如果有人帮助我做短而有效的话,那么我将非常感谢他/她。
答案 0 :(得分:2)
应该作为连接表而不是一系列子查询。
SELECT DISTRICT_ID FROM DISTRICT
inner join city on district.district_id = city.district_id
inner join city_info on city.city_id = city_info.city_id
inner join station_house on station_house.city_pin = city_info.city_pin
inner join officer_history on officer_history.station_id = station_house.station_id
inner join officer on officer.officer_id = officer_history.officer_id
and officer.design_id= design
and officer.status_type = 'ACTIVE'
and officer.zone_id = zone
请注意,连接SQL文本和变量会让您对SQL注入攻击开放,因此如果您对SQL查询感兴趣,请将SQL查询转换为参数化查询。