473,769 Members | 1,683 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting results from one table by rows in another table

HaLo2FrEeEk
404 Contributor
I've got a table where I store tips for a challenge. Its structure is this:

tip_id, challenge_id, user_id, ip_address, tip_date, tip_text

The tips can be voted up or down, I store vote data in another table, which looks like this:

tip_id, ip_address, vote_date, vote

The similar column between the two is tip_id. Vote is a bool, 0 means a vote down, 1 means a vote up.

My page will initially display one tip per challenge, but there will be a page that will show all tips for the specified challenge. In an effort to reduce my query count, I devised this query:

Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.   V.vote AS vote,
  3.   T.tip_id AS tip_id,
  4.   T.tip_date AS tip_date,
  5.   T.tip_text AS tip_text
  6.   FROM votes V
  7.     LEFT JOIN tips T
  8.     ON V.tip_id = T.tip_id
  9.   WHERE T.challenge_id = 1
  10.   ORDER BY T.tip_id ASC
Which returns a new row for each vote and a copy of the tip data for each one. As an example, I inserted a test tip and 3 test votes, running this query returns 3 rows with the 3 votes, and 3 copies of the tip data, and I know that's how it's supposed to work. What I'd like to do is have it return one row per tip, with the count of up and down votes, sorted by the difference of up and down. By this I mean that if there are two tips, a and b:

a: 3 up, 2 down (diff: 1)
b: 4 up, 1 down (diff: 3)

Then b would come first and a would come second, since b has a higher overall score.

I really don't care how complicated the query is, I just can't think of how I could do it in PHP.

Oh, and in addition to the overall rating I also need the individual up and down values. Using the above example for b, I'd like this result:

Expand|Select|Wrap|Line Numbers
  1. up | down | rating | tip_id | tip_date | user_id | tip_text
  2. 4  | 1    | 3      | 1      | 12345678 | 1       | "This is some text"
Can someone suggest me a way to do this? It's sorta the defining feature of my project, letting people vote on submitted tips and having higher-rated tips appear higher in the list.

Edit: As a side note here's the query I'm currently using to get the up / down counts for a specified tip:

Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.   count(CASE WHEN vote = 1 THEN 'up' ELSE NULL END) AS up,
  3.   count(CASE WHEN vote = 0 THEN 'down' ELSE NULL END) AS down
  4.   FROM votes
  5.   WHERE tip_id = 1
I tried modifying it a little to try to include everything from the tips table as well, like this:

Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.   count(CASE WHEN V.vote = 1 THEN 'up' ELSE NULL END) AS up,
  3.   count(CASE WHEN V.vote = 0 THEN 'down' ELSE NULL END) AS down,
  4.   T.*
  5.   FROM votes V, tips T
  6.   WHERE V.tip_id = 1
And it sorta worked, but for some reason the up and down count are double what they should be, so if a tip has 2 up votes, the number displayed is actually 4. No clue why, any ideas?

Edit 2: I should also note that if a challenge ID has more than one tip associated with it, then the query should return each tip in it's own row. A problem I'm having right now is that I'm getting a total count of up and down votes for all tips for the specified challenge, in a single row. The problem with the two queries I posted in the first edit is that they perform the query based on the value of the tip_id, which means I can only get 1 tip at a time. I need to return all tips for the challenge, so I need to perform the query using the value of challenge_id.
Mar 22 '11 #1
1 1924
HaLo2FrEeEk
404 Contributor
I just figured I'd post an answer here. Since no help was forthcoming, I asked the same question on StackOverflow and got the answer I was looking for. MY final query is a lot simpler than I expected it to be, and I'm really happy to be learning about [LEFT/INNER/OUTER] JOIN, it's so useful! Here's the query I'll be using:

Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.   COUNT(CASE WHEN V.vote = 1 THEN 'up' ELSE NULL END) AS up,
  3.   COUNT(CASE WHEN V.vote = 0 THEN 'down' ELSE NULL END) AS down,
  4.   (COUNT(CASE WHEN V.vote = 1 THEN 'up' ELSE NULL END)-COUNT(CASE WHEN V.vote = 0 THEN 'down' ELSE NULL END)) AS rating,
  5.   T.*
  6.   FROM tips T
  7.   LEFT JOIN votes V
  8.   ON T.tip_id = V.tip_id
  9.   WHERE T.challenge_id = 10
  10.   GROUP BY T.tip_id
  11.   ORDER BY rating DESC
All I have to provide to it is the challenge_id, it'll do all the work from there. The best part is, because of the LEFT JOIN, tips that don't have any votes will still appear in the result, with their up, down, and rating fields set to 0.

I posted this so that someone in the future with a similar problem can have the resource.
Mar 24 '11 #2

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

Similar topics

9
19608
by: Deja User | last post by:
This is probably very simple but I can't figure out a way to update one table from another table. Here is an example: ------ TABLEA ------ first_name last_name
1
31169
by: Mike9900 | last post by:
What is the best way to copy DataRow from one table to another table, without copying its structure, which means copying only its data. -- Mike
1
1738
by: thengfen | last post by:
Hi! Im having a problem in transfering a set of records from a table to another table. The scenario is when i select combo box (Course taken such as diploma in IT), then the process will automatically save the list of subjects that need to be taken by students into student course info table.. i hv link all the related table together... I had tried a few solution but still cant... Hope somebody can help.... Thanks a lot! :)
1
2252
by: satishkhachane | last post by:
-------------------------------------------------------------------------------- I want to select one or more columns from one typed datatable and add it to another table . how I can do this ? Eg :- table master it has column masterid , mastername now i select masterid and assign it to new comlunm.
1
2008
by: Sakakini | last post by:
How can I append last entry from one table to another table???
4
4851
by: xoozlez | last post by:
Hi there, How do I insert new records from a dbo table to another table? This is what I have: 1 dbo_company 1 Member (table) I made a query in dbo_company with the criteria I only want to retrieve out new records from "ceo_email" and "contact_email" column after e.g 25.July.07
2
2239
by: tomash | last post by:
Hi! I ve got two tables in Access 2007. I want to update a field of DataTable from another table, DataSumTable when two of their fields equals. ( the fields : Name and Period) I tried this sql code: UPDATE DataTable
5
5328
by: eBob.com | last post by:
I am so frustrated. I've been working all weekend on what I thought would be a simple script. I never find it easy to look at someone else's code, but if someone can help with this I would be very grateful. The script is .... <script type="text/javascript"> var parentwin = external.menuArguments; var doc = parentwin.document; var x = doc.getElementsByTagName("table") alert(x.length + " table things")
3
2595
by: anil2083 | last post by:
How to migrate the comma separated values from one table to another table? suppose we have table i.e XYZ and we have comma separated values in few columns i.e( column_name and values are A,B,C,D).Now i have to migrate these comma separated values into new table i.e PQR. Example: Table1 column_name1 complexion values : VF,F,AVG etc.. column_name2 profession values : TEA,LECT etc...
0
9415
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10198
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10032
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9978
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9848
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5293
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5432
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3947
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2810
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.