0

我正在加入 3 张桌子。

table1.
grp_id | email_id
   1   |  3 
   1   |  58

table2.
sam_msg_id | sam_subject
   3       |  Funnel

table3.
id | subject
58 | testing check


Desired Output:

id |grp_id|email_id|sam_subject|subject      |
184|1     |3       |funnel     |             |
185|1     |58      |           |testing check|

我试过的查询:

SELECT table1.*, table2.sam_subject, table3.* 
FROM table1
INNER JOIN table2 
    ON table2.sam_msg_id = table1.email_id 
INNER JOIN table3 
    ON table3.id = table1.email_id 
WHERE table1.grp_id = '1' 

我在这里要做的是从 table2 和 table3 中获取主题列表及其 id,其中 id 在 email_id 下的 table1 中找到。

当我尝试仅通过仅检查 table2 中的数据来使用一个内部连接时,它正在工作。

我不熟悉使用内部连接,因此我看不出我做错了什么。

我正在使用 MySQL。

4

2 回答 2

3

Sounds like you need a LEFT JOIN

SELECT table1.*, table2.sam_subject, table3.* 
FROM table1
LEFT JOIN table2 
    ON table2.sam_msg_id = table1.email_id 
LEFT JOIN table3 
    ON table3.id = table1.email_id 
WHERE table1.grp_id = '1' 

Based on you edit, the following should give you the results you want:

SELECT t1.grp_id, 
  t1.email_id, 
  coalesce(t2.sam_subject, '') sam_subject, 
  coalesce(t3.subject, '') subject
FROM t1
left JOIN t2 
    ON t2.sam_msg_id = t1.email_id 
left JOIN t3 
    ON t1.email_id = t3.id
WHERE t1.grp_id = '1' 

See SQL Fiddle with Demo

于 2012-08-13T21:29:53.903 回答
1

I'm a bit confused about what you are asking. If you can provide an example of your current data and your desired output we can probably nail down a solution.

As it is, I suspect you need to read up on LEFT JOIN, which will return NULL if there is no matching record in your child table. INNER JOIN will not return a record if there is no match.

Take a look at this article for an explanation of the different types of joins:

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

UPDATE:

I'm not sure where the first column of your desired results is coming form but the query below should get you the desired results:

SELECT t1.*, t2.sam_subject, t3.subject
FROM Table1 as t1
LEFT JOIN table2 as t2
on t1.email_id = t2.sam_msg_id
LEFT JOIN table3 as t3
on t1.email_id = t3.id
于 2012-08-13T21:29:58.513 回答