简体   繁体   中英

How can I model this database in order to handle this query

There is a source who provides data in the following format, and I have to designed tables based on this format. Should I keep their existing structure or break them up into several tables?

The first table:

ItemId     PropertyId      Value

A1           10            Black
A1           20            16gb
A1           30            Iphone6
A1           1000          Apple

The property reference table:

PropetyID     Value

10            Color
20            Memory Size
30            Item Name
100           Product Group

There can be more than 2000 distinct properties. The table designed at the end should be capable of answering the following question:

How many white iPhones of 16gb were sold?

This design looks good to me, as it doesn't break any noticeable normalization rules. In addition, this is designed in a way to write the query you are looking for.

Because I suspect this is a homework question, I am not going to write your entire query for you, but I will give you a rough guideline, and you will have to convert it to SQL. To find white 16 gb iPhones:

  • Select itemIDs where value 10 is equal to white, value 20 is equal to 16gb and value 30 is equal to iPhone.
  • Since these conditions cannot hold true on each row, you need to query for rows matching one of those conditions (hint: OR operator).
  • That being said, you will then need to find out which itemIDs matched all three of those conditions (hint: HAVING clause).

A rough skeleton:

SELECT items
FROM myTable
WHERE itemIsWhite OR itemIs16gp OR itemIsIphone
GROUP BY item
HAVING threeRowsReturned

If you get stuck on anything feel free to ask, but I highly recommend you try this on your own, as I have given you a lot to start with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM