mysql通过比较两个不同的条件从两个不同的表中获取结果

sycxhyv7  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(350)

又是我奇怪的问题。

table users:

id | type | partner | company
------------------------------
 1 |   2  |   0     | comp1
 2 |   3  |   2     | comp2
 3 |   3  |   2     | comp3
 4 |   3  |   3     | comp4

table orders:

id | user | partner
--------------------
 1 |  2   |   2
 2 |  2   |   2
 3 |  2   |   3
 4 |  3   |   2

我知道跟踪这些数字有点难。我以身份登录 type 2 (users表)并希望从 ordersuserstype 3 它们被列为我的 partners (partner 2) 另外,我想要 company 名字来自
users table 我的成绩也是如此。查询将在 orders table。

result:

id | user | partner | company
------------------------------
 1 |  2   |   2     | comp2
 2 |  2   |   2     | comp2
 4 |  3   |   2     | comp3

事先谢谢你,如果你不明白这个问题,问我。我会尽量解释的更好,任何编辑,使它更清楚也欢迎。

zbsbpyhn

zbsbpyhn1#

也许是这个

select s.id,
        case when src = 'u' then s.users
        else s.partner
        end as users,
        case when src = 'p' then s.users
        else s.partner
        end as partner,
        u.company
    from
   (
   select 'u' as src,id,users,partner from o where users = 2 and (users = partner)
   union
    select 'p',id,partner,users from o where partner = 2 and (users <> partner)
    ) s
    join u on u.id = s.partner
    where type = 3;

希望不言自明,注意我只需要了解用户,查询出合作伙伴。
结果

+------+-------+---------+---------+
| id   | users | partner | company |
+------+-------+---------+---------+
|    2 |     2 |       2 | comp2   |
|    1 |     2 |       2 | comp2   |
|    4 |     3 |       2 | comp3   |
+------+-------+---------+---------+
3 rows in set (0.00 sec)

相关问题