从同一用户的两个表中获取数据?

时间:2011-03-27 16:22:52

标签: php mysql

我有两个表格问答。

- questions{id,user_id,question,date}
- answers {id,q_id,user_id,answer, date}

我想检索由同一用户输入的问题和答案

 i.e. select all answer and all questions for ID=39 order by date DESC

并且在我有查询之后,我想通过获取数组并显示数据,我如何区分它是问题还是答案,所以我可以正确显示它们。

编辑:

SELECT 'Q' AS
TYPE , q.question AS value, q.date
FROM questions q
WHERE q.user_id =39
UNION ALL SELECT 'A' AS
TYPE , q.question AS value, a.date
FROM answers a,questions q
WHERE a.q_id = q.id
AND
WHERE a.user_id =39
ORDER BY `date` DESC

我很抱歉,但我试图得到已经回答的问题而不是答案本身。我在顶部更新了sql和数据库设计,但我一直收到错误

4 个答案:

答案 0 :(得分:2)

SELECT 'Q' as `type`,
       id,
       user_id,
       question as quesion_or_answer,
       `date`
FROM   questions
WHERE  user_id = 39
UNION ALL
SELECT 'A' as `type`,
       id,
       user_id,
       answer as quesion_or_answer,
       `date`
FROM   answers
WHERE  user_id = 39
ORDER  BY `date`  DESC

答案 1 :(得分:2)

使用:

  SELECT 'Q' AS type,
         q.question AS value,
         q.date
    FROM QUESTION q
   WHERE q.user_id = ?
UNION ALL
  SELECT 'A' AS type,
         a.answer AS value,
         a.date
    FROM ANSWER a
   WHERE a.user_id = ?
ORDER BY `date` DESC

UNIONUNION ALL用于组合查询以返回单个结果集。 UNION删除重复项; UNION ALL不会删除重复项,因此会比UNION更快。但是UNION'd语句中所有SELECT语句的SELECT子句中需要有相同数量的列。他们的数据类型必须在每个位置匹配。

为区分答案和问题值,示例定义静态值“A”代表答案,“Q”代表问题。您的应用程序层代码可以解决这些问题,以根据需要格式化数据。

答案 2 :(得分:0)

我会懒惰并使用UNION ALL,因为它只是连接两个表:

SELECT *, NULL as answer FROM questions WHERE ID=39
UNION ALL
SELECT *, NULL as question FROM answers WHERE ID=39
ORDER BY date DESC

后期差异化的技巧是使用空字段或其他标识符。

答案 3 :(得分:-1)

由于问题和答案之间似乎没有关系:使用单独的查询。