按时间戳排序所有联合结果

时间:2018-04-18 04:42:08

标签: mysql sql

查询

SELECT L.timestamp AS timestamp . . . 
FROM like AS L 
INNER JOIN users AS U 
ON U.id = L.user_id 
INNER JOIN posts AS P 
ON P.user_id = :userid 
WHERE L.post_id = P.id 
  UNION 
SELECT P.timestamp . . . 
FROM post AS P 
INNER JOIN users AS U 
ON U.id = P.user_id 
WHERE FIND_IN_SET(:userid , P.users) 
  UNION 
SELECT C.timestamp AS timestamp . . . 
FROM comment AS C 
INNER JOIN posts AS P 
ON P.user_id = :userid 
INNER JOIN users AS U 
ON U.id = C.user_id 
WHERE C.post_id = P.id 
ORDER BY timestamp DESC

我尝试在最后添加ORDER BY timestamp DESC,但它仍然没有首先显示最新的<input id="cart-<?php /* @escapeNotVerified */ echo $_item->getId() ?>-qty" name="cart[<?php /* @escapeNotVerified */ echo $_item->getId() ?>][qty]" data-cart-item-id="<?php /* @escapeNotVerified */ echo $_item->getSku() ?>" value="<?php /* @escapeNotVerified */ echo $block->getQty() ?>" type="number" size="4" title="<?php echo $block->escapeHtml(__('Qty')); ?>" class="input-text qty" maxlength="12" data-validate="{required:true,'validate-greater-than-zero':true}" data-role="cart-item-qty"/> <a class="pic arrow-right qty" href="javascript:void(0);" onclick="increaseQTY('cart-<?php /* @escapeNotVerified */ echo $_item->getId() ?>-qty');"></a> <script> function increaseQTY(formid) { document.getElementById(formid).value ++; } </script> 。它显示了一个; 10天前,9天前,1个月前,4天前,按此顺序。

2 个答案:

答案 0 :(得分:2)

您需要将查询用作子查询,以便对整个结果执行ORDER BY

SELECT * FROM (
    SELECT L.timestamp AS timestamp FROM like AS L 
        INNER JOIN users AS U ON U.id = L.user_id 
        INNER JOIN posts AS P ON P.user_id = :userid 
    WHERE L.post_id = P.id 
    UNION
    SELECT P.timestamp . . . FROM post AS P 
        INNER JOIN users AS U ON U.id = P.user_id 
    WHERE FIND_IN_SET(:userid , P.users) 
    UNION 
    SELECT C.timestamp AS timestamp . . . 
    FROM comment AS C 
        INNER JOIN posts AS P ON P.user_id = :userid 
        INNER JOIN users AS U ON U.id = C.user_id 
    WHERE C.post_id = P.id 
)x ORDER BY x.timestamp DESC

答案 1 :(得分:2)

您不需要将整个查询放在from子句中。您可以在每个子查询周围加上括号。这在documentation

中明确说明
  

使用ORDER BY或LIMIT子句对整个UNION进行排序或限制   结果,括起单个SELECT语句并放置   最后一个之后的ORDER BY或LIMIT。

所以:

(SELECT L.timestamp AS timestamp . . . 
 FROM like L JOIN
      users U 
      ON U.id = L.user_id JOIN
      posts P 
      ON P.user_id = :userid 
 WHERE L.post_id = P.id 
) UNION
(SELECT P.timestamp . . . 
 FROM post P JOIN
      users U 
      ON U.id = P.user_id 
 WHERE FIND_IN_SET(:userid , P.users) 
) UNION 
(SELECT C.timestamp AS timestamp . . . 
 FROM comment C JOIN
      posts P 
      ON P.user_id = :userid JOIN
      users U 
      ON U.id = C.user_id 
 WHERE C.post_id = P.id 
)
ORDER BY timestamp DESC;

注意:如果您的子查询未返回重复行,请将UNION更改为UNION ALL。没有必要承担删除重复项的开销。