How do I create a query that display every parent with its children rather than to display all parents first then children. For example, right now, the mySQL table shows all COMPUTERS and then DRIVES. I want it to display for every computer, display the drives associated with that computer. I.E.:
COMPUTER DRIVE PID ID
dell 1
apple 2
apple 3
hp 4
hp 5
WD300FV 1
WD440GB 1
WD55 2
WD44X 2...
I want it displayed like this where every computer is shown a list of its drives:
COMPUTER DRIVE PID
dell 1
WD300FV 1
WD440GB 1
apple 2
WD55 2
WD44X 2
apple 3.....
Where computer has a parent ID and drive has an ID.
When I do this query SELECT * FROM table it doesn’t create rows as I would like it to be displayed. I want every row that shows a computer to display a list of drives below the computer row.
I would question your table structure. I would think computers and drives should be in two separate but related tables, since they are two different things, potentially with their own properties.
computer table:
computer_id would be auto-incrementing primary key
drive table:
drive_id would be auto-incrementing primary key
computer_id would have index (and possibly foreign key constraint if you are using InnoDB and wanted to enforce a relationship to computer table)
Then you would query like this:
If, for whatever reason, you didn’t want to go with a normalized structure like I have proposed and instead use a de-normalized structure like similar to what you already have, you should at least consider doing your de-normalization in a more sane way. There is no need for your
pidlogic at all if you just structured your table like this:You are just adding a level of complexity that doesn’t need to be there. You could easily sort your result by “computer”:
With no schema changes at all you could query like this: