简体   繁体   中英

Query two tables ORDER BY date

So I have two tables that displays values like a Facebook look-a-like feed. They both have a datetime column named date , but I want them to order them together by date 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:

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.

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.

If you're unsure, I suggest looking at tutorials / examples / documentation which show what JOIN does, and what UNION does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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