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=o wner.id OR owned.owner2=ow ner.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!
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=o wner.id OR owned.owner2=ow ner.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!
Comment