Web Hosting Talk







View Full Version : Sorting a table by the results of another table (MySQL/PHP)


jon31
07-10-2007, 06:39 PM
Hey folks,

I have two tables. One table (tableA) contains an item, and the second table (tableB) contains an ever growing list of rows related to items in tableA. Say, for example, that item1 in tableA has 8 rows in tableB, and item2 has 4 rows. How can I make item1 appear at the top of the list, then item2? Because of my old version of MySQL, I can't use Group By.

PHP Version 4.3.2
MySQL 3.23.58

mwatkins
07-10-2007, 07:12 PM
If I understand your situation correctly...

Table A
----------------
id
thing_name

Table B
----------------
id
table_a_id
some_attribute
some_other_attribute


SELECT b.id, b.some_attribute FROM tableb b, tablea a
WHERE b.table_a_id = a.id
ORDER BY b.table_a_id, some_other_attribute;

Oops, re-reading this you clearly care about the number of rows in TableB.

count and group by solve this; if you don't have those available to you, doing the grouping in code seems to be the remaining door left open for you.

jon31
07-10-2007, 07:26 PM
That seems to be sorting by the value of "some_other_attribute". Am I correct? I'm trying to sort by the number of rows in tableB that correspond to the one Item in tableA

mwatkins
07-10-2007, 07:50 PM
I was just giving an example of a multi-level sort - in case your tableB had something meaningful in it like

Table A
id (key)
name (Product Group)

Table B
product_group_id (fkey)
name (Product Name)

Otherwise, just ORDER BY b.table_a_id

jon31
07-10-2007, 07:51 PM
Ah, I see. I will give that a shot and let you know of my results!