dsgrs26202 2011-08-29 01:27
浏览 51
已采纳

从2个表中获取内容?

I want a query to grab results from 2 different tables where a specific user has added the row. So my 2 tables look like this:

addresses

  • id
  • address
  • user_id

emails

  • id
  • email
  • user_id

So, I want to pull the content from both tables where the user_id row equals 1. For context, imagine each user can add multiple addresses and emails to the site and I want to grab them all to display on their profile pages.

So I tried this:

SELECT *  
  FROM addresses
  JOIN emails USING (user_id) 
 WHERE user_id = '1'

However this doesn't work - It either returns 2 of each row from the first table, or nothing at all. I also tried this:

SELECT * 
  FROM addresses, 
       emails 
 WHERE user_id = '1'

But this also returns nothing.

  • 写回答

5条回答 默认 最新

  • douli8040 2011-08-29 03:24
    关注

    Simple Union Version:

    Select user_id, address as details from addresses
    where user_ID = 1
    UNION 
    Select user_id, email as details from emails
    where user_ID = 1
    

    Here is some quick reading on union: http://www.tizag.com/sqlTutorial/sqlunion.php

    From Input

    table1:                        table2
    
    id  user_id  address           id    user_id   email
    ----------------------         ----------------------
    1   1        Add1              1       1       Email1
    2   1        Add2              2       1       Email2
    3   2        Add3              3       2       Email3
    4   2        Add4              4       3       Email4
    

    The results will be

    user_id     details
    -----------------------
    1           Add1
    1           Add2
    1           Email1
    1           Email2
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog