如何在postgresql中忽略选择不同的列?

发布于 2024-09-06 14:12:27 字数 771 浏览 7 评论 0原文

大家好!

我有一个 SQL(见上文),我想知道如何确保我不会只得到与名称有关的双打。如果名称出现在第一个选择中,则它是主选择,并且在以下选择中应被忽略。

"SELECT name, id, 'place' AS tablename FROM places WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."UNION SELECT name, id, 'community' AS tablename FROM communities WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."UNION SELECT name, id, 'district' AS tablename FROM districts WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."UNION SELECT name, id, 'region' AS tablename FROM regions WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."UNION SELECT name, id, 'province' AS tablename FROM provinces WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."ORDER BY name LIMIT 10"

这是我的 SQL。

你需要更多信息吗?

谢谢

Hello everybody!

I have a SQL (see above) and i would like to know how i can make sure that i don't get doubles concerning the name only. if a name appears in the first Select it's the master and should be ignored in the following selects.

"SELECT name, id, 'place' AS tablename FROM places WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."UNION SELECT name, id, 'community' AS tablename FROM communities WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."UNION SELECT name, id, 'district' AS tablename FROM districts WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."UNION SELECT name, id, 'region' AS tablename FROM regions WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."UNION SELECT name, id, 'province' AS tablename FROM provinces WHERE lower(name) LIKE '".strtolower($needle)."%'"
    ."ORDER BY name LIMIT 10"

this is my SQL.

do u need more information?

thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

初见你 2024-09-13 14:12:27

DISTINCT

SELECT DISTINCT ON (name) name, id, tablename 
FROM (
    SELECT name, id, 'place' AS ... 
    UNION ... 
    UNION ... 
    UNION ... 
    UNION ...) AS subQuery
ORDER BY name LIMIT 10

只需指定仅通过使用查询作为子查询来对name 进行区分即可。

在distinct期间进行限制和排序,否则distinct可能会丢弃重复项并且不会按照正确的排序顺序放弃完整的10行。

DISTINCT

SELECT DISTINCT ON (name) name, id, tablename 
FROM (
    SELECT name, id, 'place' AS ... 
    UNION ... 
    UNION ... 
    UNION ... 
    UNION ...) AS subQuery
ORDER BY name LIMIT 10

Just specify to only do distinct on the name by using your query as a sub-query.

Do the limit and ordering during the distinct, otherwise the distinct might discard dupes and not give up the full 10 rows in the correct sorted order.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文