如何在一个查询中通过排序从 2 个表中选择不同的值?
我有
- table1 :
country
,theOrderColumn1
- table2 :
country
,theOrderColumn2
我想加入 DISTINCT country< /code> 来自这两个 SELECT 语句:
SELECT DISTINCT `country` FROM `table1` ORDER BY `theOrderColumn1`
以及
SELECT DISTINCT `country` FROM `table2` ORDER BY `theOrderColumn2`
示例:
table1 (country, theOrderColumn1): (uk, 1), (usa, 2)
table2 (country, theOrderColumn2): (france, 1), (uk, 2)
我想要这个结果:
france
uk
usa
I have
- table1 :
country
,theOrderColumn1
- table2 :
country
,theOrderColumn2
I want to join DISTINCT country
from these two SELECT statements:
SELECT DISTINCT `country` FROM `table1` ORDER BY `theOrderColumn1`
and
SELECT DISTINCT `country` FROM `table2` ORDER BY `theOrderColumn2`
Example:
table1 (country, theOrderColumn1): (uk, 1), (usa, 2)
table2 (country, theOrderColumn2): (france, 1), (uk, 2)
I want this result:
france
uk
usa
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您想同时保留
theOrderColumn1
和theOrderColumn2
给出的顺序,可以使用列索引来指定ORDER BY
列。看看这个问题的答案:SQL 查询 - 在 UNION 中使用 Order By
If you want to preserve order given by
theOrderColumn1
andtheOrderColumn2
at the same time, you can use the column index to specify theORDER BY
column.Take a look at the answers to this question: SQL Query - Using Order By in UNION
但如果表 1 和表 2 中的 OrderColumn 不同,您将会得到重复项。
Though you will get duplicates if theOrderColumn is different in table 1 and table 2.
这取决于您想要什么以及如何将两个表连接在一起。如果您基于“theOrderColumn”加入,那么查询将是“
如果您想跨国家/地区加入”(这没有意义,因为两个表中的国家/地区将相同),那么您可以在联接中交换“国家/地区”条款。
此外,根据您的 DBMS 使用的 SQL 方言,您的情况可能会因上述查询而异。你能更清楚地说明你所追求的是什么吗?
It depends on what you are wanting and how you want to join the two tables together. If you are joining based on "theOrderColumn", then the query would be
If you want to join across country (which wouldn't make sense as the country would be identical in both tables) then you could swap out "country" in the join clause.
Also, depending on your SQL dialect spoken by your DBMS, your mileage may vary with the above query. Can you clarify more of what you are after?