473,396 Members | 1,998 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Need help with complicated query!

1
Hi People,

I need some help with a SQL query... I have a number of tables in my database and I would like to be able to filter out just 1 list with certain information:

The 2 most important tables are:

Expand|Select|Wrap|Line Numbers
  1. Table: users
  2. Columns: name, age, gender
  3. data example: Anaticula87, 22, m
  4. data example: Tweeke, 25, m
  5. data example: augustusmeisje, 40, f

Expand|Select|Wrap|Line Numbers
  1. Table: weather
  2. Columns: date, hour, temp, clouds, rain, snow
  3. data example: 20020101, 1, -1, 4, 0, 1
  4. data example: 20020605, 4, 135, 2, 0, 0
  5. data example: 20060213, 23, 46, 6, 1, 0
Then a bit more complicated... I have a table for every user, named 'playlist_' + 'username'.

Expand|Select|Wrap|Line Numbers
  1. Table: playlist_anaticula87
  2. Columns: UTSID, date, hour, artist, song, tag1, tag2
  3. data example: 1183449088, 20070703, 2, The Chemical Brothers, The Big Jump, electronic, rock
  4. data example: 1183413662, 20070703, 3, The Chemical Brothers, Come Inside, electronic, rock
  5. data example: 1183182450, 20070630, 8, Incubus, When It Comes, rock, indie

So my goal is:

Filter out a list based on gender, age, time and weather conditons with a combined count for every genre (tag1&tag2)

For example: Get list for Female users, aged 25 when it was raining (rain = 1)

Result:

Expand|Select|Wrap|Line Numbers
  1. genre                    plays
  2. -------------------------------------------------
  3. Rock                     10230
  4. Jazz                     2765
  5. RnB                      89
  6. Electronic               728
  7. etc
  8. etc

Now I'm very new to SQL so I find this quite hard.. I hope to be able to do this in 1 query that I can send with PHP..

But any solutions to this are more than welcome.. Whoever can help me with this.. I owe you HUGE!

Thanks!
Jan 19 '10 #1
1 1303
Atli
5,058 Expert 4TB
Hey.

There is one huge flaw in your database design, which - amongst other things - makes the query you are trying to build much more complicated than it needs to be.

Your "playlist_<username>" tables. As a general, and rather important, rule-of-thumb: you should never have to modify the table structure to accommodate new data. - In your case, because your playlist tables are named after your users, it is practically impossible to dynamically search all the various playlist_user tables without manually editing the queries to insert the names.

What you should be doing is creating one big playlist table, adding the ID of the user as a foreign key to link each row to it's respective user.
Expand|Select|Wrap|Line Numbers
  1. +---------------+    +-----------------+
  2. | user          |    | playlist        |
  3. +---------------+    +-----------------+
  4. | id (PK)       |1--N| user_id (FK)    |
  5. | name          |    | UTSID (PK)      |
  6. | etc...        |    | date            |
  7. +---------------+    | hour            |
  8.                      | artist          |
  9.                      | song            |
  10.                      | tag1            |
  11.                      | tag2            |
  12.                      +-----------------+
See what I mean?
There you would have all the playlist data in a single table, which simplifies the query you are asking about immensely.

It may look something in the direction of:
Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.         pl.genre,
  3.         COUNT(*) AS 'plays'
  4. FROM    playlist AS pl
  5. INNER JOIN weather AS w
  6.         ON w.date = '<insert date>'
  7.         AND w.hour = 12
  8.         AND w.rain = 1
  9. INNER JOIN users AS u
  10.         ON u.age = 25
  11.         AND u.gender = 'm'
  12. GROUP BY pl.genre
(Disclaimer: this was written after being awake for ~23 hours, and after being coffein deprived for the last 10 hours, so this -probably- won't work out-of-the-box xD)


P.S.
Also, note that your "tag1" and "tag2" fields violate the 1NF (First Normal Form): you should not have multiple columns in a single table that store the same type of data.

What would happen, for example, if in the future you needed to add "tag3"? You would have to modify all the preexisting data to add the third tag, and every row would HAVE TO have 3 tags. - Ideally, you should be able to add as many, or as few, tags per row as is needed, and not a single, fixed amount. To fix this, you would pull the "tagN" fields out of the table and into a separate table.
Expand|Select|Wrap|Line Numbers
  1. +---------------+    +-----------------+    +----------------+
  2. | user          |    | playlist        |    | tag            |
  3. +---------------+    +-----------------+    +----------------+
  4. | id (PK)       |1--N| user_id (FK)    |    | tag_name (PK)  |
  5. | name          |    | UTSID (PK)      |1--N| UTSID (FK, PK) |
  6. | etc...        |    | date            |    +----------------+
  7. +---------------+    | hour            |
  8.                      | artist          |
  9.                      | song            |
  10.                      +-----------------+
Truth be told, there is a more "normalized" design for this situation, but that's a different conversation. This should do fine to begin with.

Also, both the "artist" and "song" fields should ideally be in their own tables to. The "artist" is not really dependent on the ID of the playlist; it's fairly independent in that context. Similarly, the "song" relies on the "artist", and not the "playlist", and as such does not belong in the "playlist" table.

... But that is a discussion for another time. For now your goal can be achieved using the structre I suggested. - Best to put this stuff on the TODO list :)

P.P.S
What sort of fields are your "date" and "hour" fields? They look sort of like strings, based on you example data. Is that so?
If it is, you really should check out MySQL's Date and Time types. Will most likely save you a ton of working in the future: to get used to them sooner rather than later.
Jan 20 '10 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Adam i Agnieszka Gasiorowski FNORD | last post by:
I need help width formulating the most effective (in terms of processing time) SQL query to count all the "new" documents in the repository, where "new" is defined as "from 00:00:01 up to...
0
by: B. Fongo | last post by:
------=_NextPart_000_0014_01C363E8.FDC5B160 Content-Type: text/plain; charset="us-ascii" Content-Transfer-Encoding: 7bit Hello again! I was able to extra the information from the first 2...
0
by: B. Fongo | last post by:
I learned MySQL last year without putting it into action; that is why I face trouble in formulating my queries. Were it a test, then you would have passed it, because your queries did help me...
2
by: William Wisnieski | last post by:
Hello Everyone Access 2000 Looking for some suggestions and advice on how to proceed with this. I hope its not as complicated as it seems to me right now. I've got an unbound main form...
4
by: Bob | last post by:
Hallo, I have to make a web application in Javascript/ASP for tenniscourt reservation (based on Access database). I would like to do everything with one page, because the user must be able to...
5
by: hubmei75 | last post by:
Hello, I have a simple table containing adresses. A sample view of the table is id name city -------------------------------- 100 Meier New York 101 Meier Tokyo 110 ...
3
by: eagleofjade | last post by:
I am trying to help a friend who is learning VB.net in school. I have done VB programming for a number of years using VB 6. He needs to open a query in an Access database that has parameters so he...
0
by: Chuck36963 | last post by:
Hi all, I've been working on a listing problem and I can't figure out how to work it out. I have looked far and wide on the web to find answers, but I'd like other peoples input on my project in...
1
by: mskapek | last post by:
I need some advise on how to best create an Access 2002 report from multiple "total" queries, each which result in 3- 5 values that I need displayed on my report. Most of the queries do simple...
5
by: LadyIlsebet | last post by:
I'm not a fantastic Access developer, but I'm trying to help get Inventory and whatnot organized at work. They are used to 5 year budget plans that list out exactly what has to be purchased what...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.