UNION

时间:2018-03-12 16:43:38

标签: mysql

我有这个问题:

SELECT category, description, price, date_added, datetime_created
FROM vc_expense
WHERE trip_id=? AND description LIKE ?
GROUP BY description, price    

UNION SELECT category, description, NULL, NULL, NULL
FROM vc_expense_default
WHERE description LIKE ?    

ORDER BY CASE
  WHEN description LIKE ? AND price THEN 1
  WHEN price THEN 2
  ELSE 3
END, date_added DESC, datetime_created DESC
LIMIT 5

我的问题是,当我对第4行的描述+价格进行分组时,它并没有考虑到我想要最新的结果:

date_added DESC, datetime_created DESC

有没有办法在第4行之后使用ORDER BY,这样我才能获得最新的项目,因为UNION似乎无法工作

谢谢!

编辑:    UNION是无关紧要的,我只是把它放在了parantheses中,并且只从每个组获得最新的项目,如下所示:

SELECT e1.category, e1.description, e1.price, e1.date_added, e1.datetime_created
FROM vc_expense e1
LEFT JOIN vc_expense e2 ON (
    e1.description=e2.description AND
    e1.price=e2.price AND
    e1.date_added < e2.date_added
)
WHERE e2.id IS NULL AND e1.trip_id = ? AND e1.description LIKE ?

1 个答案:

答案 0 :(得分:1)

来自文档: https://dev.mysql.com/doc/refman/5.7/en/union.html

  

对单个SELECT语句使用ORDER BY意味着什么   因为UNION,行在最终结果中出现的顺序   默认情况下会生成一组无序行

这就是你需要的:

  

要将ORDER BY或LIMIT应用于单个SELECT,请放置该子句   在括起SELECT的括号内:

(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);