简体   繁体   English

查询两个表 ORDER BY 日期

[英]Query two tables ORDER BY date

So I have two tables that displays values like a Facebook look-a-like feed.因此,我有两个表格,显示类似于 Facebook 的提要之类的值。 They both have a datetime column named date , but I want them to order them together by date DESC.他们都有一个名为datedatetime时间列,但我希望他们按日期 DESC 将它们一起排序。

I think join is the correct way(?), but not quite sure.我认为加入是正确的方式(?),但不太确定。 Can someone help me out?有人可以帮我吗?

Currently I have them in two different queries:目前我有两个不同的查询:

$status1 = "1";
$stmt1 = $link->prepare('
SELECT id
     , ident_1
     , ident_2
     , date
     , ident_1_points
     , ident_2_points 
  FROM duel 
 WHERE active=? 
 ORDER 
    BY date
');
$stmt1-> bind_param('s', $status1);

and

$status2 = "OK";
$stmt2 = $link->prepare('SELECT id, ident, pp, date FROM sales WHERE status=? AND team IN (2, 3) ORDER BY date DESC LIMIT 20');
$stmt2->bind_param('s', $status2);

How should I do this?我该怎么做?

If you want one continuous list containing data from both tables, and the whole thing ordered by date overall, then you might need a UNION query in a subquery, and then order the outer query, something like this:如果您想要一个包含两个表中数据的连续列表,并且整个内容按日期排序,那么您可能需要在子查询中使用 UNION 查询,然后对外部查询进行排序,如下所示:

SELECT * 
FROM
(
  SELECT id, ident_1, ident_2, date, ident_1_points, ident_2_points
  FROM duel 
  WHERE active=?

  UNION ALL

  SELECT id, ident, pp, date, NULL, NULL 
  FROM sales 
  WHERE status=? 
    AND team IN (2, 3)
  LIMIT 20
) list
ORDER BY date DESC 

The requirement isn't 100% clear to be honest from your description (sample data and expected results always helps when asking SQL questions), but I think this is pretty close to what you need.从您的描述中说实话,该要求并不是 100% 清楚(示例数据和预期结果在询问 SQL 问题时总是有帮助),但我认为这非常接近您的需求。

JOIN doesn't seem appropriate, unless you want a result set where items from each table are linked to each other by some common field, and you combine them such that you get all the columns side by side, showing the data from one table next to the data which matches from the other table. JOIN似乎不合适,除非您想要一个结果集,其中每个表中的项目通过某个公共字段相互链接,然后将它们组合在一起,以便并排获取所有列,显示下一个表中的数据到与另一个表匹配的数据。

If you're unsure, I suggest looking at tutorials / examples / documentation which show what JOIN does, and what UNION does.如果您不确定,我建议您查看教程/示例/文档,其中显示了 JOIN 的作用以及 UNION 的作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM