MySQL项目设计 - 有条件地从一个表中选择基于另一个选择查询的行

时间:2013-11-05 12:12:33

标签: mysql join project

我在MySQL数据库中有2个表,它们定期附加新数据。一个是出租物业及其特征的列表,例如2床,2浴,位置,租赁价格等。第二个表是当前待售的物业列表。从租赁表中我可以使用查询确定特定类型的财产在特定位置获得的平均租金:

SELECT bed, bath, type, suburb, postcode, AVG(price)
FROM rent_suburbs
GROUP BY bed, bath, type, suburb, postcode

我希望能够从buy_items表中选择属性,其中用户定义的销售价格百分比小于匹配类型和位置的属性的平均租赁价格。

我正在尝试修改有人建议的代码,但我被卡住了。

select listing, bed, bath, type, address, postcode, state, price
from 
   buy_items
where (price*.0014) < avg(price) from 
select 
    bed, bath, type, suburb, postcode, avg(price)
from
    rent_items
group by bed , bath , type , suburb , postcode
/* and bed, bath, type, suburb and postcode match the buy_items property ????

我很新,所以感谢任何帮助。感谢

表结构如下:

buy_items

buy_items_id2   int(11)
car         int(11)
price   int(11)
listing varchar(12)
bed         int(11)
bath    int(11)
suburb  varchar(25)
state   int(11)
scrapedate  int(11)
address varchar(45)
type    varchar(25)
postcode    int(11)

rent_items

rent_items_id2  int(11)
car         int(11)
price   int(11)
listing int(11)
bed         int(11)
bath    int(11)
suburb  varchar(25)
state   varchar(5)
scrapedate  int(11)
address varchar(45)
type    varchar(25)
postcode    int(11)

1 个答案:

答案 0 :(得分:1)

试试这个:

   select listing, b.bed, bath, type, address, postcode, state, price
    from 
       buy_items b
    join (
    SELECT bed, bath, type, suburb, postcode, AVG(price) as avg_price
    FROM rent_suburbs
    GROUP BY bed, bath, type, suburb, postcode ) a
    on a.bed=b.bed and a.bath=b.bath and a.suburb=b.suburb and a.postcode=b.postcode
    where (b.price*.0014) < a.avg_price;