Ordering MySQL results to obey parent/child

Asked
Active3 hr before
Viewed126 times

8 Answers

orderingmysqlresults
90%

You cannot do it only with SQL queries (at least in MySQL). One of the approaches with SQL and PHP is the following:,and you call it once with:,Connect and share knowledge within a single location that is structured and easy to search.,Each row is therefore a chapter heading, but there can be chapters within chapters, within chapters. Therefore the table above allows me to maintain these relationships.

You cannot do it only with SQL queries (at least in MySQL). One of the approaches with SQL and PHP is the following:

SELECT id, IFNULL(parent_id, 0) AS parentid, chapter FROM toc ORDER BY parentid, display_order
load more v
88%

I have a table like this:,I want to create a ordered form like this:,In the database there are many books, not just one.,my table looks something like this: so my aim is to select only values where the name is 'z' and not NULL. The second condition is that the values that correspo...

I have a table like this:

ID NAME TYPE PARENT
1 Letters of Jane Austen book 0
2 Chapter 1 chapter 1
3 Chapter 2 chapter 1
4 Chapter 3 chapter 1
5 Title 1 title 2
6 Title 2 title 2
load more v
72%

Note: I've added COALESCE(Parent_ID_Asset, '') just to get NULL Parent_ID in first place, you could replace it by CASE WHEN Parent_ID_Asset IS NULL THEN 0 ELSE 1 END,You can get it by using CASE WHEN in ORDER BY clause:,Parent on top, followed by children in alphabetical order. The parent elements (with null in Parent_ID_Asset) must be also ordered alphabetically., Business Learn more about hiring developers or posting ads with us

Note: I've added COALESCE(Parent_ID_Asset, '') just to get NULL Parent_ID in first place, you could replace it by CASE WHEN Parent_ID_Asset IS NULL THEN 0 ELSE 1 END

SELECT
ID_Asset,
Parent_ID_Asset,
ProductTitle
FROM
Test
ORDER BY
CASE WHEN Parent_ID_Asset IS NULL THEN ID_Asset ELSE Parent_ID_Asset END,
COALESCE(Parent_ID_Asset, ''),
   ProductTitle;
GO

   |
   ID_Asset | Parent_ID_Asset | ProductTitle |
   |
   -- -- -- -- -- | -- -- -- -- -- -- -- -- - | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- |
   |
   2 | NULL | Live Maps Unity |
   |
   3 | NULL | mShare |
   |
   4 | NULL | Nessus Professional |
   |
   5 | NULL | Enterprise Server |
   |
   6 | NULL | PhantomPDF |
   |
   7 | NULL | Sharegate |
   |
   8 | NULL | ADONIS Server |
   |
   16 | 8 | ADONIS Designer |
   |
   20 | 8 | ADONIS Portal ModuleControl & ReleasePackage XS |
   |
   9 | NULL | Automated Intelligence AI Compliance Extender & AI Syncpoint |
   |
   10 | NULL | Agility BridgeChecker |
   |
   11 | NULL | Office Timeline |
   |
   12 | NULL | ThinkBuzan iMindMap 8 Ultimate |
   |
   13 | NULL | Total Management Suite |
   |
   14 | NULL | Webex Business Messaging and Advanced Meetings |
load more v
65%

SELECT child.Id,
   child.Name,
   child.ParentId,
   parent.Name as ParentName
FROM your_table child
JOIN your_table parent ON child.ParentId = parent.id;
75%

The fastest data generation solution is as follows: Insert the required number of rows into each parent table Get the ids according to the data generation logic and use them to add rows to the child table ,In this tip I will show you a single statement solution I came up with in PostgreSql and SQL Server and I would love to hear your comments on how you would solve this challenge. ,Get the ids according to the data generation logic and use them to add rows to the child table,On my laptop, I generated 100,000 rows using the below technique. In SQL Server it took 86 seconds compared to the 3 statements logic (like below) which took approximately 5 minutes.

create database nested_inserts;

CREATE TABLE public.product(
   productid serial NOT NULL,
   product_name varchar(256) NOT NULL,
   color varchar(30) NULL,
   listprice money NOT null,
   CONSTRAINT pk_product_productid PRIMARY KEY(productid)
);

CREATE TABLE public.salesperson(
   salespersonid serial NOT NULL,
   territoryid int4 NULL,
   salesquota money NULL,
   bonus money NOT null,
   CONSTRAINT pk_salespersonid PRIMARY KEY(salespersonid)
);

CREATE TABLE public.salesorderheader(
   salesorderid serial not null,
   salespersonid int4 NOT NULL,
   productid int4 NOT NULL,
   orderdate timestamp NOT NULL,
   shipdate timestamp NULL,
   status int2 NOT null,
   CONSTRAINT pk_salesorderheader_salesorderid PRIMARY KEY(salesorderid),
   CONSTRAINT fk_salesorderheader__salesperson_salespersonid FOREIGN KEY(salespersonid) REFERENCES public.salesperson(salespersonid),
   CONSTRAINT fk_salesorderheader__product_productid FOREIGN KEY(productid) REFERENCES public.product(productid)
);
load more v
40%

Make sure it uses index It is very important to have ORDER BY with LIMIT executed without scanning and sorting full result set, so it is important for it to use index – in this case, index range scan will be started and query execution stopped as soon as required amount of rows generated.,Could you suggest improvement that I can do in following query. It’s taking 8 seconds to execute and I am afraid it will take more as table fill up with more data.,This is pretty bad idea. You did not write what you do ORDER BY but it may require filesort. But even if you do it by index in average 50% of rows will have to be scanned because of LIMIT.,But you must NOT include ORDER BY score DESC if you want your query executed in decent time. I will require Filesort which can take very long:

For queries that combine ORDER BY with LIMIT, the optimizer may switch to an index that applies to the ORDER BY. In some cases, the decision to switch was based on a heuristic rather than on cost. The optimizer now uniformly makes the decision whether to switch on a cost basis. This should result in better performance when switching would cause a query to read an entire index or a large part of it to find qualifying rows.
References: See also: Bug #78993, Bug #22108385, Bug #73837, Bug #19579507, Bug #16522053.

ORDER BY

For queries that combine ORDER BY with LIMIT, the optimizer may switch to an index that applies to the ORDER BY. In some cases, the decision to switch was based on a heuristic rather than on cost. The optimizer now uniformly makes the decision whether to switch on a cost basis. This should result in better performance when switching would cause a query to read an entire index or a large part of it to find qualifying rows.
References: See also: Bug #78993, Bug #22108385, Bug #73837, Bug #19579507, Bug #16522053.

LIMIT

For queries that combine ORDER BY with LIMIT, the optimizer may switch to an index that applies to the ORDER BY. In some cases, the decision to switch was based on a heuristic rather than on cost. The optimizer now uniformly makes the decision whether to switch on a cost basis. This should result in better performance when switching would cause a query to read an entire index or a large part of it to find qualifying rows.
References: See also: Bug #78993, Bug #22108385, Bug #73837, Bug #19579507, Bug #16522053.

ORDER BY
load more v
22%

My MySQL query at the moment, which of course doesn't order the results as I desire:, Existing user? Sign In , MySQL Help , MySQL Help

SELECT * FROM pages GROUP BY id ORDER BY FIELD(child, '1', '0') DESC, id DESC
load more v
60%

One of the most common situations to deal with is when there are more than one foreign key path between two tables.,relationship() will normally create a join between two tables by examining the foreign key relationship between the two tables to determine which columns should be compared. There are a variety of situations where this behavior needs to be customized.,Therefore, to get at all of #1, #2, and #3, we express the join condition as well as which columns to be written by combining relationship.primaryjoin fully, along with either the relationship.foreign_keys argument, or more succinctly by annotating with foreign():,Changed in version 1.0.0: the ORM will attempt to warn when a column is used as the synchronization target from more than one relationship simultaneously.

from sqlalchemy
import Integer, ForeignKey, String, Column
from sqlalchemy.ext.declarative
import declarative_base
from sqlalchemy.orm
import relationship

Base = declarative_base()

class Customer(Base):
   __tablename__ = 'customer'
id = Column(Integer, primary_key = True)
name = Column(String)

billing_address_id = Column(Integer, ForeignKey("address.id"))
shipping_address_id = Column(Integer, ForeignKey("address.id"))

billing_address = relationship("Address")
shipping_address = relationship("Address")

class Address(Base):
   __tablename__ = 'address'
id = Column(Integer, primary_key = True)
street = Column(String)
city = Column(String)
state = Column(String)
zip = Column(String)
load more v

Other "ordering-mysql" queries related to "Ordering MySQL results to obey parent/child"