[英]combine ORDER BY in UNION query
how do i combine ORDER BY in UNION query?我如何在 UNION 查询中组合 ORDER BY?
I tried this and got error:我试过这个并得到错误:
SELECT country.country_name AS res
FROM countries AS country
WHERE (lower (country.country_name) LIKE '%".$_POST['query']."%')
ORDER BY country.lang = '".$_POST['lang']."'
UNION
SELECT sec.loc AS res
FROM itin_secs AS sec
WHERE sec.loc LIKE '%".$_POST['query']."%'
I would recommend:我会推荐:
SELECT res
FROM (SELECT c.country_name as res, 1 as priority, c.lang
FROM countries AS c
WHERE lower(c.country_name) LIKE '%".$_POST['query']."%')
UNION ALL -- recommended instead of `UNION`
SELECT sec.loc Ares
FROM itin_secs as sec, 2, NULL
WHERE sec.loc LIKE '%".$_POST['query']."%'
) x
ORDER BY priority, lang = '".$_POST['lang']."';
This query is quite explicit about the final ordering.这个查询对最终排序非常明确。 It also uses
UNION ALL
, so the query does not incur the overhead of removing duplicates.它还使用
UNION ALL
,因此查询不会产生删除重复项的开销。
As a secondary issue (I mean, the original query doesn't work), you should parameterize the query.作为次要问题(我的意思是,原始查询不起作用),您应该参数化查询。 You should really start by writing parameterized queries, so they are natural for anything you want to do.
您应该真正开始编写参数化查询,因此它们对于您想做的任何事情都是很自然的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.