在我的数据库中,我有一个名为 data_countries
的表,其结构如下:
country | population | nearby_country1 | nearby_country2 | nearby_country3
当我运行以下查询时
SELECT DISTINCT data_countries.country, data_countries.population, data_countries.nearby_country1 , data_countries.nearby_country2 , data_countries.nearby_country3
FROM data_countries
WHERE data_countries.country = 'Netherlands'
我得到的结果看起来像这样
Netherlands | 16570613 | Belgium | Germany | United Kingdom
我现在真正想要实现的目标如下。
基于输入“Netherlands”,我还想以相同结构返回 nearby_country1
nearby_country2
和 nearby_country3
列的数据。
具体来说,我想调整我的查询以获得如下输出:
Netherlands | 16570613 | Belgium | Germany | United Kingdom
Belgium | 10000000 | Netherlands | Other | Other
Germany | 10000000 | Netherlands | Other | Other
United Kingdom | 10000000 | Other | Other | Netherlands
我研究了INNER JOIN
和Subselect
并尝试了一些东西,但似乎无法做到正确。
希望有人能让我在这方面找到正确的方向。
谢谢
最佳答案
恶心。您的数据未标准化,因此您需要通过联接来执行此操作。如果您的 table 不是很大,这是一种方法。请注意,该国家/地区本身包含在“附近”国家/地区中:
select nearby.*
from data_countries c join
data_countries nearby
on c.country = 'Netherlands' and
nearby.country in (c.country, c.nearby_country1, c.nearby_country2, c.nearby_country3)
order by (nearby.country = 'Netherlands') desc;
如果您想保持排序,请将order by
更改为:
order by (nearby.country = 'Netherlands') desc,
(nearby.country = c.nearby_country1) desc,
(nearby.country = c.nearby_country2) desc,
(nearby.country = c.nearby_country3) desc
编辑:
Here是一个 SQL Fiddle 示例,显示它的工作原理(请注意,这使用 SQL Server,以便我可以使用 with
语法)。
标准化意味着您有一个名为 NearbyCountries
的表,其中包含两个数据列。一个用于第一个国家,一个用于第二个国家。
关于php - MySQL 在同一查询中使用查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21205688/