好吧,我有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。如果我使用相同的查询来获取这些邮政编码,那么它就无法正常工作。可能是我错了。
答案 0 :(得分:2)
从我们的讨论结果我们最终得到:
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;