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 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏