1

I have a table Fruit like this:

Name Property Value
Apple Price $5
Apple Color Red
Apple Quantity 20
Pear Price $5
Pear Color Kelly
Pear Weight 50g
Pear Quality Good

Now I want to select all records of Pear that are different from Apple in either Property or Value (The result will be the last 3 rows)

In C# it will be

foreach(var apple in apples)
{
   var result = pears.All(pear => pear.Property != apple.Property && pear.Value != apple.Value)
}

In SQL Server I tried this but failed:

    Select * from Fruit where Name = 'Pear'
and exists
(select 1 from Fruit t where t.Name = 'Apple'
and t.Property <> Fruit.Property
and t.Value <> Fruit.Value)

How should I correct the SQL statement? Thanks.

6
  • 4
    That's a very poorly normalized table! If this is from a real-life application you really should do something about it. Commented Dec 27, 2020 at 16:11
  • 1
    But apples can be red and green (and other colours). How would you know what property belongs to another? Your design needs fixing here. Commented Dec 27, 2020 at 16:16
  • Apologizes. That's my first time to use Table here. It looked OK when I previewed it. But lost format after I posted this question. Thanks for the comment and edit. Commented Dec 27, 2020 at 16:17
  • @GertArnold isn't talking about how you presented the tables they are saying your design in your actual database is flawed. Commented Dec 27, 2020 at 16:19
  • 1
    EAV strikes again! If you are designing your own database, then research that term to understand the consequences and the very real problems you will face trying to extract meaningful information from it. Commented Dec 27, 2020 at 16:22

1 Answer 1

3

You can use not exists:

select f.*
from fruit f
where f.name = 'Pear' and
      not exists (select 1
                  from fruit f2
                  where f2.name = 'Apple' and
                        f2.property = f.property and
                        f2.value = f.value
                 );
Sign up to request clarification or add additional context in comments.

Comments

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.