简体   繁体   English

如何在一个查询中选择以下数据

[英]How to select following data in one single query

I am using postgres 我正在使用postgres

Table 1: person 表1:人

Columns:: id,person_name,person_add,block_id
FK==>person(block_id) reference block(id)

Table 2: block 表2:块

Columns:: id,block_name,district_id
FK==> block(district_id) reference district(id)

Table 3: district 表3:区

Columns:: id,district_name,state_id
FK==> district(state_id) reference state(id)

Table 4: state 表4:状态

Columns:: id,state_name,country_id
FK==> state(country_id) reference country(id)

Table 5: country 表5:国家

Columns:: id,country_name

i have written query as follow:: 我写查询如下:

When i want block wise details 当我想要明智的细节时

SELECT p.id,p.person_name,b.block_name,d.district_name,s.state_name,c.country_name
FROM person p 
INNER JOIN block b ON b.id = p.block_id
INNER JOIN district d ON d.id = b.district_id
INNER JOIN state s ON s.id = d.state_id
INNER JOIN country c ON c.id = s.country_id
WHERE b.id = ? OR d.id = ? OR s.id = ? OR c.id = ?

how to write it in single query for following cases ??? 在以下情况下如何在单个查询中编写它?

1.i have only country id and s.id,d.id,b.id are going to be null(here above query gives fine result) 1.我只有国家/地区ID,而s.id,d.id,b.id将为null(此处上述查询给出了很好的结果)

2.i have country id and state id and d.id,b.id(here it will prefer according to c.id) 2.我有国家ID和州ID以及d.id,b.id(这里根据c.id会更喜欢)

3.i have country id, state id and district id b.id(same here it will prefer according to c.id) 3.i有国家ID,州ID和地区ID b.id(相同,根据c.id会更喜欢)

4.i have country id,state id,district id and block id is null(same here it will prefer according to c.id) 4.我有国家/地区ID,州/省/自治区/直辖市/直辖市/自治区,并且id为null(相同,此处将根据c.id优先考虑)

If I understand correctly the criteria is optional. 如果我正确理解该标准是可选的。 You may be searching for a certain country, state, district and block or for instance only for a country. 您可能正在搜索某个国家,州,地区和街区,或者仅搜索某个国家。

So check each variable for null. 因此,请检查每个变量是否为空。 Something like this: 像这样:

SELECT p.id,p.person_name,b.block_name,d.district_name,s.state_name,c.country_name
FROM person p 
INNER JOIN block b    ON b.id = p.block_id
INNER JOIN district d ON d.id = b.district_id
INNER JOIN state s    ON s.id = d.state_id 
INNER JOIN country c  ON c.id = s.country_id
WHERE (b.id = :block_id    OR :block_id is null)
  AND (d.id = :district_id OR :district_id is null)
  AND (s.id = :state_id    OR :state_id is null)
  AND (c.id = :country_id  OR :country_id is null);

(You can also move the conditions to the ON clauses; whichever you prefer.) (您也可以将条件移动到ON子句;随便哪个。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM