从Mysql中的用户和报表查询

时间:2014-07-03 06:01:17

标签: mysql

 User Table   
 ------------
| id | Name |
|------------
| 1  |  A   |
| 2  |  B   |
| 3  |  C   |
| 4  |  D   |
 ------------

 report Table   
 --------------------
| id | uid | status |
|--------------------
| 1  |  1   |   0   |
| 2  |  3   |   1   |   
| 3  |  2   |   0   |
| 4  |  3   |   1   |
 --------------------

假设我有两个表用户和报告。我想根据状态列对报告表进行查询,即

  

WHERE status = 0

但我的问题是我不想要uid,我想从用户表中获取用户名但是怎么做?请帮忙。

3 个答案:

答案 0 :(得分:0)

也许是这样的:

加入语法

SELECT
    User.id,
    User.Name
FROM
    User
    JOIN report
        ON User.id=report.uid
WHERE
    report.status=0

EXISTS语法

SELECT
    User.id,
    User.Name
FROM
    User
WHERE EXISTS
(
    SELECT
        NULL
    FROM
        report
    WHERE
        report.status=0
        AND User.id=report.uid
)

IN语法

SELECT
    User.id,
    User.Name
FROM
    User
WHERE User.id IN
(
    SELECT
        report.uid
    FROM
        report
    WHERE
        report.status=0
)

参考:

答案 1 :(得分:0)

SELECT 
  User.Name 
FROM 
  User 
  JOIN report 
    ON User.id=report.uid 
WHERE 
  report.status=0

答案 2 :(得分:0)

您必须使用INNER JOIN之类的

SELECT u.id,
       u.Name
FROM USER u
INNER JOIN report r ON u.id=r.uid
WHERE r.status=0;