Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
学习SQL:使用声明的INT从单独的表中返回特定值,然后在where函数中使用_Sql - Fatal编程技术网

学习SQL:使用声明的INT从单独的表中返回特定值,然后在where函数中使用

学习SQL:使用声明的INT从单独的表中返回特定值,然后在where函数中使用,sql,Sql,我正在学习SQL的基础知识,并使用SQL爬山器来实现这一点,虽然这很简单,但我已经尝试解决了几个小时 问题是我可以通过输入'Italy'正确返回数据,但我需要使用INT返回意大利的国家ID。我该怎么做呢?还是有一种更简单的方法让我错过了 DECLARE @TouristAttractionId INT = 8 Select 'City' = ci.Name, 'Attraction' = ta.Name, 'Description' = ta.Description

我正在学习SQL的基础知识,并使用SQL爬山器来实现这一点,虽然这很简单,但我已经尝试解决了几个小时

问题是我可以通过输入'Italy'正确返回数据,但我需要使用INT返回意大利的国家ID。我该怎么做呢?还是有一种更简单的方法让我错过了

DECLARE @TouristAttractionId INT = 8

Select 
    'City' = ci.Name,
    'Attraction' = ta.Name,
    'Description' = ta.Description
from city ci
join Country c on c.Id = ci.CountryId
join TouristAttraction ta on ta.CityId = ci.Id

where c.Name = 'Italy'

Union

Select 
    'City' = ci.Name,
    'Attraction' = ta.Name,
    'Description' = ta.Description
from city ci
join Country c on c.Id = ci.CountryId
join TouristAttraction ta on ta.CityId = ci.Id

where ta.Id =@TouristAttractionId

order by ci.Name, ta.Name asc

Answer :

SELECT 
    City = ci2.Name
   ,Attraction = ta2.Name
   ,ta2.Description
FROM TouristAttraction ta1
JOIN City ci1 ON ci1.Id = ta1.CityId
JOIN City ci2 ON ci2.CountryId = ci1.CountryId
JOIN TouristAttraction ta2 ON ta2.CityId = ci2.Id
WHERE ta1.Id = @TouristAttractionId
ORDER BY ci2.Name, ta2.Name

这是通过创建包含附加联接的重复表来解决的问题

无需在此处进行联合。简单地说,或者两个WHERE子句的条件。嗨,贾尔赫,如果我不使用union,我只有一行数据返回,我希望意大利的所有旅游景点都返回。我必须使用声明的INT来获得国家,这是我被卡住的部分,因为我不知道如何做到这一点?
    City = ci2.Name
   ,Attraction = ta2.Name
   ,ta2.Description

FROM TouristAttraction ta1

JOIN City ci1 ON ci1.Id = ta1.CityId
JOIN City ci2 ON ci2.CountryId = ci1.CountryId
JOIN TouristAttraction ta2 ON ta2.CityId = ci2.Id

WHERE ta1.Id = @TouristAttractionId

ORDER BY ci2.Name, ta2.Name