doucan8276 2013-11-17 20:41
浏览 84
已采纳

使用内连接的相当复杂的SQL语句(我推测)

I'm having trouble figuring out how to write an SQL query to return results from the following table structure.

The first thing I do is get a list of clients that have a status equal to 1 by:

SELECT * FROM clients WHERE status=1

Then I need to get all user email addresses that belong to a client. My plan was to loop through the results of the query above and running multiple queries for each client. As you can see from the table 'client_user_list' a single user can belong to multiple clients.

I tried doing something like this:

SELECT emailaddress 
FROM users 
INNER JOIN client_user_list ON users.user_id = client_user_list.user_id 
WHERE users.client_id = 1

But it failed. As you can see I'm a total novice when it comes to this stuff. Any help would be appreciated, or feel free to point me to an appropriate resource to learn more. I've looked, but I haven't found anything that covers something complex like this.

Additional info: Using foreign keys there are relationships between clients <-> client_user_list and client_user_list <-> users

clients:
|---------------------------------------|
|  client_id  |  client_name   | status |
|---------------------------------------|
|      1      |    John Doe    |    1   |
|      2      |    James Doe   |    0   |
|---------------------------------------|

client_user_list:
|----------------------|
| client_id  | user_id |
|----------------------|
|     1      |    5    |
|     2      |    6    |
|     1      |    6    |
|----------------------|

users:
|---------------------------------------|
|   user_id   |       emailaddress      |
|---------------------------------------|
|      5      |     notan@email.com     |
|      6      |     afake@email.com     |
|---------------------------------------|

Thanks so much in advance.

  • 写回答

3条回答 默认 最新

  • dongxian6285 2013-11-17 20:46
    关注

    I'm not sure if this is your only problem, since you didn't specify what the exact problem is, but the WHERE-clause of your query contains an error. You query should be changed into this:

    SELECT DISTINCT emailaddress 
    FROM users 
    INNER JOIN client_user_list ON users.user_id = client_user_list.user_id 
    WHERE client_user_list.client_id = 1
    

    The users table does not have a field called client_id, the client_user_list table does.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料