Question

I am writing an MySQL database unfortunately I was instructed to not use foreign keys and that the foreign keys would just be assumed. This has made the project extremely awkward to say the least. However I am trying to derive a solution to a problem. I have an entity table; This table is called "Sale", "Sale" holds the attribute/foreign Key Music ID or "MID"(INT). "MID" is the primary key of another table called "Music" with the attributes "Artist"(String) and "Title"(String) which represent the title and artist's of various songs respectively. My question Is how would I go about creating a query/function that will go into sale extract the "MID" value for each row so the whole "MID" column then go to the "Music" table and Adds up every time the "Artist" and "Title" of the extracted "MID" column appears. Despite there being no actual foreign keys I must write the query as if there is so I am trying to avoid storing the extracted "MID" content into a separate table. I was able to write a statement that should extract the "MID" I am just struggling to figure out how to wrap a statement around it that adds up the total amount of times the "Artist" and "Title" are referenced. Oh an BTW different "MID" values can have the same "artist" or "Title" so I must account for that.

SELECT  SELECT MID FROM Sale 
      WHERE SDate<= CURDATE();

This code extracts The MID values from any date prior to the current date.(That is another stipulation that the MID's must be from the earliest recorded date to the current Date this is because some Dates in Sale are for future reference, I.E. There dates are in the future.

Was it helpful?

Solution

Use a JOIN:

SELECT Artist, Title, IFNULL(COUNT(s.MID), 0) SalesCount
FROM Music AS m
LEFT JOIN Sale AS s ON m.ID = s.MID AND SDate <= CURDATE()
GROUP BY Artist, Title

If this isn't what you need, please make a sqlfiddle with sample data, and post the result you're trying to get in your question. Your description is confusing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top