更改PostgreSQL查询的结构

时间:2015-09-08 08:43:36

标签: sql postgresql select join

我有以下PostgreSQL查询,它基本上返回基于硬编码产品名称的推荐列表(故意拼写错误)。

有4个表 -

Products_list

Column     |          Type          | Modifiers
---------+------------------------+-----------
productid | integer                | not null
name      | character varying(400) | not null
year      | character varying(100) | not null

分类

 Column    |         Type          | Modifiers
---------+-----------------------+-----------
 productid | integer               | not null
 category  | character varying(50) | not null

公司

Column   |          Type          |   Modifiers            
---------+------------------------+------------
compid  | integer                | not null
c_name  | character varying(250) | not null

Prod_com

Column  |  Type   | Modifiers
---------+---------+-----------
productid | integer |
compid | integer |

用户输入拼写错误的产品名称,我会找到最匹配的产品名称,然后找到相应的类别和生产该产品的公司,并推荐由属于同一类别的同一公司生产的产品列表。

With 
product_name as (
select name,productid
from products_list
group by name,productid
having levenshtein(name, 'Acryn')<=3
order by levenshtein(name, 'Acryn')
LIMIT 1 OFFSET 1
),
cat_name as( 
select distinct category, c.productid productid
from product_name m, categories c
where m.productid=c.productid 
),
com_name as(
select distinct c_name,a.compid compid
from companies a, prod_com pc, product_name m
where pc.productid = m.productid and pc.compid=a.compid 
LIMIT 2)
select distinct name,year
from products_list pl, cat_name cn, com_name co, prod_com pc,categories c
where co.compid=pc.compid and c.category = cn.category and 
c.productid = pl.productid and pl.productid = pc.productid
limit 10;

我班上的一名学生已经使用了类似的WITH子句方法,我的教授希望我以不同的方式做。我已经付出太多努力,我不知道如何更改查询结构,以便它与上述查询完成相同的工作。

有人可以帮助我重新构建此查询,以便它以相同的方式工作吗?感谢。

1 个答案:

答案 0 :(得分:0)

WITH
foo as (select subquery)
select bar from foo

相当于

select bar from (select subquery) as foo

http://www.postgresql.org/docs/current/static/queries-with.html

相关问题