按日期从2个表中订购数据

时间:2013-04-10 06:37:58

标签: php mysql sql-order-by

我有3个表:myMembers,forum_question和forum_answer。 myMembers:

id | usr ..|..| follow | ....
 1 | Bob . |..|3,2,....|.....
 2 | John  |..|1,8,5...|.....
 3 | ......|..|........The "follow" column store the data in an array of followers id.<p>

forum_question:

id | topic .| name  | idsender      | datetime
 1 | foo q .| Bob ..|.... 1........ | 07:20
 2 | foo1 q | Bob ..|.... 1........ | 07:10
 3 | foo2 q | John .|.... 2 ........| 06:00

forum_answer:

question_id | answer | a_name | idsender | datetime
 1 .........| answ 1 | Bob ...| 1 .......| 08:20
 2 ....... .| answ 2 | Bob ...| 1 .......| 07:20
 1 .........| answ 3 | John ..| 2 .......| 08:00

我有这个:

$foll = mysql_query("SELECT follow FROM myMembers WHERE id='$id' LIMIT 1");
  while ($row = mysql_fetch_array($foll)){
    $foll1 = explode(",", $row["follow"]);
                      }
foreach ($foll1 as $key => $value){
$displ = mysql_query("SELECT p.* FROM
(SELECT id, datetime, topic, name, idsender, 'question' AS TYPE FROM 
forum_question WHERE idsender = '$value' UNION
SELECT question_id, datetime, answer, a_name, idsender, 'answer' AS TYPE FROM
forum_answer  WHERE idsender = '$value')p
ORDER BY p.datetime DESC");
        while ($row = mysql_fetch_array($displ)){
                $type= $row['TYPE'];
                $id = $row["id"];
                $topic = $row["topic"];
                $name = $row["a_name"];
                $idsender = $row["idsender"];
                $datetime=$row['datetime'];
echo '<div>'. $name .', '. $type .', '. $topic.', '. $datetime.'</div>'";

我有这个输出:

Bob, answer, answ1, 8:20
Bob, answer, answ2, 7:20
Bob, question, foo q, 7:20
Bob, question, foo1 q, 7:10
**John,** answer, answ 3, 8:00
**John,** question, foo2 q, 6:00

我想要这个输出吗?

Bob, answer, answ1, 8:20
**John,** answer, answ3, 8:00
Bob, question, foo q, 7:20
Bob, answer, answ2, 7:20
Bob, question, foo1 q, 7:10
**John,** question, foo2 q, 6:00

有可能??谢谢!

1 个答案:

答案 0 :(得分:0)

您可以将group by用于a_name并按日期时间排序。所以你的查询应该是,

$displ = mysql_query("SELECT p.* FROM
(SELECT id, datetime, topic, name, idsender, 'question' AS TYPE FROM 
forum_question WHERE idsender = '$value' UNION
SELECT question_id, datetime, answer, a_name, idsender, 'answer' AS TYPE FROM
forum_answer  WHERE idsender = '$value')p
GROUP BY p.a_name ORDER BY p.datetime DESC")