473,396 Members | 1,676 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.

adding/grouping results from union

5
I have a problem query that's not playing nice with my webhost's MySQL server. On the face of it it looks quite innocuous but I need a better way as they've forbidden me to run it any more!

Here's the situ: two tables, one has an owner ID and name, the other is for items that are owned, with an index ID and a reference to the owner ID from table 1. That's easy to manage. BUT, this is the killer, in table 2 there's also a reference for a second owner. The idea is I want to generate an ordered list of how many items are owned by each owner, but I need to combine the results of the owner ID appearing in either the first or second owner field.

Here is the (simplified) query that I can't run, using what I thought would be an obvious OR to check the two fields:

SELECT SQL_CALC_FOUND_ROWS owner.name, count(owned.id) AS numowned
FROM owner, owned
WHERE (owned.owner1=owner.id OR owned.owner2=owner.id)
GROUP BY owner.name
ORDER BY numowned DESC

It's been suggested that I can split this into a UNION of two SELECTs for each of the owner1 and owner2 fields, but I then have the problem of combining the results into a count that I can do the order by. At this point I'm stuck. Any suggestions on making this query work without the OR will be gratefully received!
May 22 '07 #1
7 2580
pradeep kaltari
102 Expert 100+
I have a problem query that's not playing nice with my webhost's MySQL server. On the face of it it looks quite innocuous but I need a better way as they've forbidden me to run it any more!

Here's the situ: two tables, one has an owner ID and name, the other is for items that are owned, with an index ID and a reference to the owner ID from table 1. That's easy to manage. BUT, this is the killer, in table 2 there's also a reference for a second owner. The idea is I want to generate an ordered list of how many items are owned by each owner, but I need to combine the results of the owner ID appearing in either the first or second owner field.

Here is the (simplified) query that I can't run, using what I thought would be an obvious OR to check the two fields:

SELECT SQL_CALC_FOUND_ROWS owner.name, count(owned.id) AS numowned
FROM owner, owned
WHERE (owned.owner1=owner.id OR owned.owner2=owner.id)
GROUP BY owner.name
ORDER BY numowned DESC

It's been suggested that I can split this into a UNION of two SELECTs for each of the owner1 and owner2 fields, but I then have the problem of combining the results into a count that I can do the order by. At this point I'm stuck. Any suggestions on making this query work without the OR will be gratefully received!
Hi Asmian,
I guess you are looking for something like this:
Expand|Select|Wrap|Line Numbers
  1. SELECT owner_name ,SUM(owned)
  2. FROM (SELECT owner_name, COUNT(*) AS owned 
  3.             FROM owner_details,item_details
  4.             WHERE owner1=id 
  5.             GROUP BY owner_name 
  6.             UNION ALL
  7.             SELECT owner_name,COUNT(*) 
  8.             FROM owner_details,item_details 
  9.             WHERE owner2=id 
  10.             GROUP BY NAME) X
  11. GROUP BY owner_name
  12.  
Please get back if you were looking for something else.

Regards,
Pradeep.
May 22 '07 #2
asmian
5
Hi Pradeep, thanks for the info. Let me look again at this, you've made a substantial edit! It looks much better than the first version you posted, which I couldn't follow at all, the syntax didn't seem familiar for MySQL.
May 22 '07 #3
asmian
5
Hi Asmian,
I guess you are looking for something like this:
Expand|Select|Wrap|Line Numbers
  1. SELECT owner_name ,SUM(owned)
  2. FROM (SELECT owner_name, COUNT(*) AS owned 
  3.             FROM owner_details,item_details
  4.             WHERE owner1=id 
  5.             GROUP BY owner_name 
  6.             UNION ALL
  7.             SELECT owner_name,COUNT(*) 
  8.             FROM owner_details,item_details 
  9.             WHERE owner2=id 
  10.             GROUP BY NAME) X
  11. GROUP BY owner_name
  12.  
Please get back if you were looking for something else.

Regards,
Pradeep.

OK, this looks good. The problem I was having was working out how to add the two results from the two SELECTs together. Can you confirm this is how this should work - in particular, your line 7 doesn't restate the alias "AS owned", is this significant? And the final "X" on line 10, what does that do?

If I add an alias to the first line "SUM(owned) AS sumboth", can I use this to do an "ORDER BY sumboth" at the end of the query too?
May 22 '07 #4
pradeep kaltari
102 Expert 100+
OK, this looks good. The problem I was having was working out how to add the two results from the two SELECTs together. Can you confirm this is how this should work - in particular, your line 7 doesn't restate the alias "AS owned", is this significant? And the final "X" on line 10, what does that do?

If I add an alias to the first line "SUM(owned) AS sumboth", can I use this to do an "ORDER BY sumboth" at the end of the query too?
Hi asmian,
1: The "AS owned" part is not required at line 7. The UNION ALL operator takes the names of the columns from the first SELECT query specified.

2: The final 'X' at line 10 is just an alias to the derived table. As you can see the FROM clause of the outer-most query consists of two SELECT statements. Now, the result of these statements is considered as a table named X. In the outer-most query you can refer to owner_name and SUM(owned) as X.owner_name and SUM(X.owned).

3: You can also add alias to the first line "SUM(owned) AS sumboth", and also you can add ORDER BY clause to it.
Expand|Select|Wrap|Line Numbers
  1. SELECT owner_name ,SUM(owned) AS sumboth
  2. FROM (SELECT owner_name, COUNT(*) AS owned 
  3.             FROM owner_details,item_details
  4.             WHERE owner1=id 
  5.             GROUP BY owner_name 
  6.             UNION ALL
  7.             SELECT owner_name,COUNT(*) 
  8.             FROM owner_details,item_details 
  9.             WHERE owner2=id 
  10.             GROUP BY NAME) X
  11. GROUP BY owner_name
  12. ORDER BY sumboth DESC, owner_name ASC
  13.  
I hope this is helpful. Please get back if you have further queries.

Regards,
Pradeep.
May 22 '07 #5
asmian
5
Hi Pradeep

Many thanks! This does exactly what I need, and it's not killing the server, which is the main thing! I've managed to add a "WHERE X.owner_name LIKE 'a%'" (etc.) successfully too, which was important.

What I need to do now is add a "LIMIT limitmin,limitmax" for the whole query, but putting it at the end is restricting the number of returned results to the limitmax number, which isn't quite what I expected. I guess the UNION is making this a little tricky and it's probably now fussy about the placing. Can it be done?
May 22 '07 #6
asmian
5
Heh, forgot my SQL_CALC_FOUND_ROWS after the first SELECT!

All working now, brilliant help Pradeep and many thanks.
May 23 '07 #7
pradeep kaltari
102 Expert 100+
Glad to help you.

Regards,
Pradeep.
May 23 '07 #8

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

Similar topics

6
by: Alan | last post by:
I'm just about to start a project that needs to combine the results of a SQL Server query with the results of an Index Server query. The basic idea is that the user enters/selects a bunch of search...
2
by: Debbie Davis | last post by:
Hi there, SQL 2000 I have the following query: SELECT sponsor, COUNT(sponsor) * 2 AS total FROM Referrals GROUP BY sponsor Works great, returns the sponsor and the total * 2 of their...
5
by: Stephen Miller | last post by:
Hi, I am trying to add a staggered running total and average to a query returning quarterly CPI data. I need to add 4 quarterly data points together to calculate a moving 12-month sum (YrCPI),...
5
by: JackT | last post by:
Hi, I have the following SQL SELECT Table1.Col1, Table3.Col1 AS Expr1, COUNT(Table1.Col2) AS Col2_No, COUNT(Table1.Col3) AS Col3_No etc, FROM Table3 INNER JOIN Table2 ON...
3
by: ahaque38 | last post by:
Hello. Using A2K SP3, I am having the following problem with a report using "Sorting and Grouping". I have recently added a grouping in the reports for "Category2<>'CONTRACTS'". I have...
3
by: UHelix | last post by:
Hi, I'm not really even sure how to phrase this question, so here is a sample of exactly what I want to do. In the following data set I would like to select the entry from the group of samples 1...
5
by: BillCo | last post by:
I'm having a problem with a union query, two simple queries joined with a union statement. It's created in code based on parameters. Users were noticing some inconsistant data and when I analysed...
1
by: bgreenspan | last post by:
Hi Everyone, I'm back for some more expert help. Here's what I am doing and what I tried. My database has entries with Contract Names and Expiry Dates, among other fields. I have a form...
11
by: Bart op de grote markt | last post by:
Hello, I have a very simple problem which I will illustrate with an example: I have the following records in my table: A 1 C A 2 C A 3 C B 8 K B 9 K
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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?
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
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...
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
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.