php - 加入具有 2 个条件的 2 个表(MySQL 和 PHP)

标签 php mysql sql

我有 2 个表:users 和 prov_spec_search。我正在寻找一个 sql 查询来连接具有以下条件的这些表:

users Table:

id | first_name | last_name | activ_status
-------------------------------------------
6  | sudha      | dravid    |    1
7  | Gokul      | menon     |    1
13 | sujith     | nair      |    1
-------------------------------------------

prov_spec_search 表

id | inv_user_id | drafter_id | activ_status
-------------------------------------------
1  | 13          | 7          |    1
2  | 13          | 6          |    1
-------------------------------------------

预期结果是:

Need to join users and prov_spec_search tables with 2 conditions where 

prov_spec_search.inv_user_id = users.id = Name

      AND 

prov_spec_search.drafter_id = users.id = Drafter name

结果:

Name       |   Drafter Name   | Active
------------------------------------------
sujit nair |   Gokul menon    |  active
sujit nair |   sudha dravid   |  active

我从这个查询开始:

SELECT
prov_spec_search.id,
prov_spec_search.inv_user_id,
prov_spec_search.drafter_id,
prov_spec_search.activ_status,
users.first_name,
users.last_name,
users.activ_status AS activ_status1
FROM prov_spec_search
INNER JOIN users ON prov_spec_search.inv_user_id = users.id AND prov_spec_search.drafter_id = users.id
WHERE (prov_spec_search.activ_status ='1')

最佳答案

您需要从 prov_spec_search 表连接到 users 表,两次:

SELECT
    pss.id,
    pss.inv_user_id,
    pss.drafter_id,
    pss.activ_status,
    CONCAT(u1.first_name, ' ', u1.last_name) AS Name,
    CONCAT(u2.first_name, ' ', u2.last_name) AS Drafter_Name
FROM prov_spec_search pss
LEFT JOIN users u1
    ON pss.inv_user_id = u1.id
LEFT JOIN users u2
    ON pss.drafter_id = u2.id
WHERE
    pss.activ_status = 1;
    -- you may filter user and drafter names here if desired

enter image description here

Demo

关于php - 加入具有 2 个条件的 2 个表(MySQL 和 PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128478/

相关文章:

php - 在 WooCommerce 中按照处理状态顺序发送其他电子邮件 (functions.php)

PHP mysqli_connect : authentication method unknown to the client [caching_sha2_password]

SQL 条件过滤器

php - 来自 PHP (CodeIgniter) 的 MySQL 调用无法正常工作

php - 使用 phpseclib 下载文件匹配模式

php - 确保相册内容新鲜

mysql - Union all,合并查询结果

C# 在选择查询中使用函数来解密表数据

php - 在 PHP 中向用户显示推荐项目的好算法是什么?

c# - 来自同一张表的 3 个不同的不同值