按列加入两个表

时间:2017-04-14 17:42:28

标签: sql google-bigquery

所以我有两个表,比如comment_table和post_table,

comment_table:

link_id   body
t3_100    people on StackOverflow are smart 
t3_100    StackOverflow is a good place to raise questions
t3_101    where can I learn sql 
t3_102    Happy Eastern
t3_102    where did my bunny go?

post_table

id      title
100     Thought on StackOverflow
101     sql beginner
102     Eastern 
105     Title that has no comments 

" link_id"由' t3 _'连接来自post_table的+ id。我想要的是两个用#34; id"加入这两个表。

预期产出

id      title                        link_id   body
100     Thought on StackOverflow     t3_100    people on StackOverflow are smart
100     Thought on StackOverflow     t3_100    StackOverflow is a good place to raise questions
101     sql beginner                 t3_101    where can I learn sql 
102     Eastern                      t3_102    Happy Eastern
102     Eastern                      t3_102    where did my bunny go?
105     Title that has no comments   t3_105    NULL

这是我的脚本,

SELECT PT.ID, PT.title, CT.link_id, CT.body  
FROM post_table as PT 
LEFT OUTER JOIN comment_table as CT
ON PT.ID = CT.concat('t3_', link_id)

它有语法错误,您认为我如何解决此问题以获得预期的输出?

5 个答案:

答案 0 :(得分:1)

您正在使用函数分配别名,它应该是字段。

这样可行。

SELECT PT.ID, PT.title, CT.link_id, CT.body  
FROM post_table as PT 
LEFT OUTER JOIN comment_table as CT
ON CT.link_id = CONCAT('t3_', PT.ID)

答案 1 :(得分:1)

在下面尝试BigQuery Standard SQL

#standardSQL
SELECT PT.ID, PT.title, CT.link_id, CT.body  
FROM post_table AS PT 
LEFT OUTER JOIN comment_table AS CT
ON CT.link_id = CONCAT('t3_', PT.ID)

答案 2 :(得分:0)

您并没有正确使用concat。试试这个:

SELECT PT.ID, PT.title, CT.link_id, CT.body  
FROM post_table as PT 
LEFT OUTER JOIN comment_table as CT
ON CT.link_id = concat('t3_', PT.id)

link_id中的comment_table是带有" t3 _"的id,所以你要连接" t3 _"使用post_table中的post_id

此外,加入这样的表非常糟糕。最好只在comment_table中使用SELECT,如果你需要附加" t3 _"出于某种原因,请在Select PT.ID, PT.title, concat('t3_', PT.id) link_id, CT.body

中进行
SELECT PT.ID, PT.title, CT.link_id, CT.body  
FROM post_table as PT 
LEFT OUTER JOIN comment_table as CT
ON CT.link_id = 't3_' + PT.id

<强>更新

由于现在显然您使用的是BigQuery而不是mysql,因此上述答案并不适用。我对BigQuery不太熟悉,但您可以尝试:

from django.contrib.auth.views import login
from django.shortcuts import redirect

def my_login(request, user):
 if request.user.is_superuser:
    #your logic here
     return redirect('/solicitar/home/')
 if request.user.is_active:
    #your logic here
    return redirect("/dashboard/")

答案 3 :(得分:0)

不确定语法本身,但似乎更明智:

concat('t3_', PT.ID) = CT.link_id

答案 4 :(得分:0)

关注ON PT.ID = CT.concat('t3_', link_id)条件。使用以下SQL。

SELECT PT.ID, PT.title, CT.link_id, CT.body  
FROM post_table as PT 
LEFT OUTER JOIN comment_table as CT
ON (CT.link_id = concat('t3_',PT.ID ))