Mysql查询从两个表中获取值

时间:2014-08-13 06:35:00

标签: mysql sql

我有两张表格如下 -

表1 MySQL的>从Access_ID中选择*;

+------------+----------------+
| SERVICE_ID | ACCESS_LIST_ID |
+------------+----------------+
|       1035 |           1040 |
|       1094 |           1134 |

表2
MySQL的>从PROFILE中选择*;

+-------+------------------------+-------------+-
| PR_ID | PR_NAME                | PR_PARENTID | PR_TYPE           |
---------------------------------------------------------------------
|  1035 | raj                    |        1022 | name           |
|  1040 | computer               |        1035 | course         |
|  1094 | suresh                 |        1077 | name           |
|  1134 | electronics            |        1077 | course         |

我需要以下输出为

| raj      |  computer  |
| suresh   | electronics|

3 个答案:

答案 0 :(得分:3)

尝试:

select
    pro1.PR_NAME
   ,pro2.PR_NAME
from 
    Access_ID acs inner join 
    PROFILE pro1 on
        (acs.SERVICE_ID = pro1.PR_ID) inner join
    PROFILE pro2 on
        (acs.ACCESS_LIST_ID = pro2.PR_ID)

答案 1 :(得分:3)

可能是这样的

SELECT T2.PR_NAME AS NAME,T3.PR_NAME AS Serveice
FROM Access_ID T1 JOIN PROFILE T2 ON T1.SERVICE_ID = T2.PR_ID 
                  JOIN PROFILE T3 ON T1.ACCESS_LIST_ID = T3.PR_ID 

<强> FIDDLE DEMO

输出

  +---------+-------------+
  | NAME    | SERVEICE    |
  +---------+-------------+
  | raj     | computer    |
  | suresh  | electronics |
  +---------+-------------+

答案 2 :(得分:0)

此查询可能会对您有所帮助


    SELECT p1.PR_NAME as Name, p2.PR_NAME as Service 
    FROM Access_ID as aid 
    LEFT JOIN PROFILE as p1 ON aid.SERVICE_ID = p1.PR_ID
    LEFT JOIN PROFILE as p2 ON aid.SERVICE_ID = p2.ACCESS_LIST_ID