php - 具有反向连接的 MySql 查询

标签 php mysql

我正在尝试构建一个查询,返回与特定机会关联的联系人列表。

我有 3 个表:联系人、机会和关系(多对多)

联系人

id   name
---------
1   Davey Jones
2   Bob Hope
3   Tiger Woods
4   Hillary Clinton

机会

id    description
------------------
1     visit the locker
2     singing and dancing
3     playing golf
4     laughing and crying

关系

id     firstid     firsttype      secondid     secondtype
---------------------------------------------------------
1      1           contact        1           opportunity
2      3           opportunity    3           contact
3      4           contact        4           opportunity
4      4           opportunity    3           contact

现在,如果我有 opportunity_id,我想返回与该机会关联的所有联系人。

所以如果opportunity_id=4,则成功查询的结果应该是:

Hillary CLinton
Tiger Woods

但这是我的查询,它只返回 1 条记录:

SELECT
contacts.name
FROM
contacts
INNER JOIN relationships ON contacts.id = relationships.secondid
INNER JOIN opportunities ON opportunities.id = relationships.firstid
where
opportunities.id=4
and (relationships.firsttype='opportunity' and relationships.secondtype='contact')
or (relationships.firsttype='contact' and relationships.secondtype='opportunity')

我不知道如何在这个查询中翻转连接。

编辑:我刚刚发现 UNION,然后尝试了这个,它似乎有效:

(select contacts.name from contacts where contacts.id =
    (select secondid as id from relationships  where (firstid = 4 and (firsttype='opportunity' and secondTtpe='contact' ) ) ) )
    UNION
 (select contacts.name from contacts where contacts.id =
    (select firstid as id from relationships where (secondid = 4 and (firsttype='contact' and secondtype='opportunity' ) ) ) )

但这看起来很笨拙。这是处理这个问题的最佳方法吗?

最佳答案

试试这个:

SELECT contacts.name FROM contacts
    inner join (
        SELECT * from relationships
        where 
            (firstid = 4 and (firsttype='opportunity' and secondtype='contact' ) )
            or 
            (secondid= 4 and (firsttype='contact' and secondtype='opportunity' ) ) 
    ) rel
    on contacts.id = rel.id;

关于php - 具有反向连接的 MySql 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26659024/

相关文章:

java - Hibernate和mysql错误: Cannot add or update a child row

mysql - SQL 左连接 : how to return the newest from tableB and grouped by another field

php - 在 Drupal 中使用 Apache Solr 按版本索引而不是节点

php - preg_match 返回奇怪的结果

php - 带有数据透视表的 Laravel 查询生成器

php - curl_exec 在尝试连接到 URL 时返回 false

php - PHP MySql 字段列表中的未知列

mysql - 配置 MySQL 服务器以避免 "MySQL Server has gone away"错误

php - 求平均和舍入的 SQL 查询

php - 无法解码某些特殊字符