繁体   English   中英

如何在Mysql中使用更多“选择查询”以从不同表中获取结果

[英]How do I use more “select query” with Mysql to get result from different table

好吧,我有3个数据库表。

1)用户
2)user_property
3)优惠

用户表结构:

----------------------------------    
id    pc1   pc2    pc3      pc4
----------------------------------
1     1205  1203   1208    1209
2     1206  1205   1209    1202
3     1207  1204   1210    1201
4     1208  1210   1211    1203
5     1209  1207   1208    1204

user_property表结构:

----------------------------------------------------    
property_id    user_id   postcode    creation_date
----------------------------------------------------
1              1         1205       02-01-2001
2              2         1206       02-03-2001
3              3         1207       02-04-2001
4              4         1205       02-05-2001
5              5         1208       02-06-2001
6              4         1205       02-07-2001

提供表结构:

-------------------------
offer_id      property_id
-------------------------
1              1         
2              2         
3              3         
4              4         
5              5         
6              4         

询问

$myQuery =  mysql_query("
 SELECT * 
   FROM user_property upr 
  WHERE (postcode = '$pc1' OR
         postcode = '$pc2' OR
         postcode = '$pc3' OR
         postcode = '$pc4') AND
         datediff(CURDATE(), upr.creation_date) <= 7 AND
         NOT EXISTS(SELECT ofr.property_id 
                      FROM offers ofr 
                     WHERE ofr.property_id = upr.property_id AND
                           ofr.agent_id IN(SELECT id 
                                             FROM users 
                                            WHERE company_name !=''
                                          )
                   )
ORDER BY property_id DESC");

在此$myQuery查询中,您可以看到( postcode = '$pc1' or postcode = '$pc2' or postcode = '$pc3' or postcode = '$pc4' ) 该邮政编码来自users表。

那么,如何从user_property表中使用1个sql查询获取这些邮政编码?

您还会看到我只是通过使用IN (select id from users where company_name !='')获得ID IN (select id from users where company_name !='') 如果我使用相同的查询来获取那些邮政编码,那么它将无法正常工作。 可能是我误会了。

从我们的讨论中,我们得出以下结论:

select 
  users.*, 
  user_property.*, 
  offers.property_id as offers_property_id 
from users 
  join user_property on users.id = user_property.user_id
    and (
          user_property.postcode = users.pc1 
      or  user_property.postcode = users.pc2
      or  user_property.postcode = users.pc3
      or  user_property.postcode = users.pc4
    )
  left join offers on 
    offers.property_id = user_property.property_id
    and offers.agent_id = users.id 

where users.company_name != ""
  and DATEDIFF(CURDATE(), user_property.creation_date) <= 7

HAVING offers_property_id IS NULL;

暂无
暂无

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

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