簡體   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