1

I've just started learning SQL. Here is part of my Database:

enter image description here

I want to get the project name from the Project table with condition:

name = 'turbine' and value = '03' in Parameter table.

I have wrote the following query and it seems to work! But I was wondering if any smarter query can do the job for me :

SELECT name
FROM Project
WHERE id IN (
    SELECT projectId
    FROM Cases
    WHERE id IN (
        SELECT caseId
        FROM ParamValue
        WHERE parameterId IN (SELECT id FROM Parameter WHERE name = 'turbine')
          AND value = '03')
    )
;
2
  • You can use JOIN() Commented Feb 20, 2020 at 16:44
  • It's better to join the tables than to do a bunch of subqueries like that Commented Feb 20, 2020 at 16:47

3 Answers 3

3

Instead of several nested IN clause with subquery seems more easy to read a proper set of inner join

select distinct Project.name 
from Project 
INNER JOIN  Cases ON Cases.projectId = Project.id
INNER JOIN ParamValue ON ParamValue.caseId = Cases.id
  AND ParamValue.value ='03'
INNER JOIN Parameter ON ParamValue.parameterId = Parameter.id 
  AND Parameter.name =  'turbine' 
Sign up to request clarification or add additional context in comments.

6 Comments

I'm getting the error : Msg 209, Level 16, State 1, Line 18 Ambiguous column name 'name'
@user9112767 Did you try changing name to Project.name (or replace Project. with the table where name comes from).
@WernerHenze, Yes, I have put the Project. before the name, but the result here is 114 rows and my select statement returns the 11 rows !
@user9112767 answer updated .. with proper table name and distinct for avoid duplication
@user9112767 the distinct clause should avoid rows duplications ...
|
1

Sure here you go without subqueries:

SELECT pj.Name
FROM Parameter p
INNER JOIN ParamValue pv ON pv.Value = '03' AND p.Id = pv.parameterId
INNER JOIN Cases c ON pv.caseId = c.Id
INNER JOIN Project pj ON c.projectId = pj.Id
WHERE p.name = 'turbine'
;

Comments

1
select pr.name from Project pr 
left join Cases c on pr.name = c.id
left join ParamValue pv on c.id = pv.parameterId
left join Parameter p on  p.id = pv.parameterId
where p.name = 'turbine' and pv.value = '03';

2 Comments

@WernerHenze, the same error with your query : Msg 209, Level 16, State 1, Line 18 Ambiguous column name 'name'
@user9112767 Not my query. I was just editing the question and fixed a type (Projetc -> Project). The answer is from Noureddine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.