mysql - 从两个表中选择位置

标签 mysql sql

我是 SQL 新手,在编写以下查询时遇到困难。

场景

一个用户有两个地址,家庭地址(App\User)和列表地址(App\Listing)。当访问者搜索郊区或邮政编码或州的列表时,如果用户的列表地址不匹配 - 但如果家庭地址匹配 - 他们也会出现在搜索结果中。

例如:如果访问者搜索Melbourne,我想包括来自Melbourne 的列表以及地址在Melbourne 的用户的列表

预期输出:

user_id first_name  email                  suburb    postcode state
1       Mathew      mathew.afsd@gmail.com  Melbourne 3000     VIC
2       Zammy       Zamm@xyz.com           Melbourne 3000     VIC

表格

用户:

id  first_name  email
1   Mathew      mathew.afsd@gmail.com
2   Zammy       Zamm@xyz.com
3   Tammy       tammy@unknown.com
4   Foo         foo@hotmail.com
5   Bar         bar@jhondoe.com.au

列表:

id  user_id hourly_rate description
1   1       30          ABC 
2   2       40          CBD 
3   3       50          XYZ 
4   4       49          EFG 
5   5       10          Efd

地址:

id  addressable_id  addressable_type    post_code   suburb     state    latitude    longitude
3584    1           App\\User           2155        Rouse Hill  NSW -33.6918372 150.9007221
3585    2           App\\User           3000        Melbourne   VIC -33.6918372 150.9007221
3586    3           App\\User           2000        Sydney      NSW -33.883123  151.245969
3587    4           App\\User           2008        Chippendale NSW -33.8876392 151.2011224
3588    5           App\\User           2205        Wolli Creek NSW -33.935259  151.156301
3591    1           App\\Listing        3000        Melbourne   VIC -37.773923  145.12385
3592    2           App\\Listing        2030        Vaucluse    NSW -33.858935  151.2784079
3597    3           App\\Listing        4000        Brisbane    QLD -27.4709331 153.0235024
3599    4           App\\Listing        2000        Sydney      NSW -33.91741   151.231307
3608    5           App\\Listing        2155        Rouse Hill  NSW -33.863464  151.271504

最佳答案

试试这个。可以查一下here .

SELECT l.*
FROM listings l
LEFT JOIN addresses a_l ON a_l.addressable_id = l.id
  AND a_l.addressable_type = "App\\Listing"
  AND a_l.suburb = "Melbourne"
LEFT JOIN addresses a_u ON a_u.addressable_id = l.user_id
  AND a_u.addressable_type = "App\\User"
  AND a_u.suburb = "Melbourne"
WHERE a_l.id IS NOT NULL OR a_u.id IS NOT NULL

关于mysql - 从两个表中选择位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37266534/

相关文章:

php - 如何使用mysql基于月份选择数据

mysql - 选择两个列值不相等的地方

mysql - 触发复合键并更新另一列

php - 管理页面访问

mysql - SQL 查询Where IN 条件

sql - oracle pl/sql ORA-01790 : expression must have same datatype as corresponding expression

mysql : get count and percent for all entries of a table with given conditions

java - 空 ResultSet 仍在评估为真,JDBC

mysql - 列出A表中的记录与B表中只有一个关系,并且在C表中有一个关系

C#:SQL - 一次一个查询与命令文本中的多个查询?