加入SQL表?

时间:2010-07-17 14:03:20

标签: sql

我有这些表格。

3 个答案:

答案 0 :(得分:1)

这是10的入门者(我假设user_id列包含用户名,但实际上可能还有另一个表):

SELECT q.question AS "Question",
       q.date_add AS "date",
       q.publish AS "publish",
       q.user_id AS "user name",
       c.name AS "category",
       a.answer AS "answer",
       a.publish AS "publish"
  FROM #__qa_question q
  LEFT OUTER JOIN #__qa_category_xref cx ON (cx.qid = q.qid)
  LEFT OUTER JOIN #__qa_category c ON (c.catid = cx.catid)
  LEFT OUTER JOIN #__qa_answer_xref ax ON (ax.qid = q.qid)
  LEFT OUTER JOIN #__qa_answer a ON (a.aid = ax.aid)

使用外部联接可确保即使没有答案或没有类别,您也会看到每个问题。

当然,如果(如外部参照表所示)每个问题有很多答案和许多类别,那么每个问题都会看到很多行,每个答案和类别组合都有一行。

答案 1 :(得分:1)

假设#__ qa_category_xref.id是FK到#__qa_answer。 (假设没有#__qa_answer_xref表。)

select q.qid as [s/n], question, q.date_modify as [date], q.publish as publish
, user_id /*as no user table specified*/, c.name as category, answer, a.publish
from #__qa_question as q
join #__qa_category_xref as xref on q.qid = xref.qid
join #__qa_answer as a on a.aid = xref.id
join #__qa_category as c on c.catid = xref.catid

答案 2 :(得分:1)


选择
q。问题,问题,
q.date_add作为日期,
q.publish as publish,
q.user_id为用户,
qcat.name作为类别,
qans.answer作为答案,
qans.publish as anspublish
来自  #__qa_question为q,
 #__qa_category_xref为qcatref,
 #__qa_category为qcat,
 #__qa_answer_xref为qansref
 #__qa_answer为qans
其中
q.qid = qcatref.qid
和qcat.catid = qcatref.catid
和q.quid = qansref.qid
和qans.aid = qansref.aid