p:lineChart not rendering - primefaces
I am trying to create a new chart in PrimeFaces 3.5RC1 but for some reason when all the data have been collected and populated in the chart it does not display on the screen. I know there is nothing wrong with the Java code because it is working but the chart is blank.
Please see java and xhtml code below:
Java Bean:
public void searchMonthTotals() {
String sql = null;
if(retailID.equals("999") && billerID.equals("999")){
sql = "WITH CTE AS("
+ " SELECT Value,DAY(IntervalStartTime) AS DAY,MONTH(IntervalStartTime) AS MONTH,YEAR(IntervalStartTime) AS YEAR, "
+ " CASE WHEN MONTH(IntervalStartTime) = MONTH(GETDATE()) THEN 'Current' ELSE 'Previous' END AS Type "
+ " FROM tblpay#Stat s (nolock) "
+ " LEFT OUTER JOIN tblPay#StatConfig c (nolock) ON s.configId = c.id "
+ " LEFT OUTER JOIN tblpay#StatSlot l (nolock) ON s.slotId = l.id "
+ " WHERE IntervalStartTime >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) "
+ " AND IntervalEndTime <= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) "
+ " AND s.configId = " + configID
+ " GROUP BY IntervalStartTime,value) "
+ " SELECT SUM(Value) AS Value, DAY,MONTH,YEAR,Type "
+ " FROM CTE "
+ " GROUP BY DAY,Type,MONTH,YEAR "
+ " ORDER BY Type ";
}else if(billerID.equals("999")){
sql = "WITH CTE AS("
+ " SELECT cm.Name AS Network,Value,DAY(IntervalStartTime) AS DAY,MONTH(IntervalStartTime) AS MONTH,YEAR(IntervalStartTime) AS YEAR, "
+ " CASE WHEN MONTH(IntervalStartTime) = MONTH(GETDATE()) THEN 'Current' ELSE 'Previous' END AS Type "
+ " FROM tblpay#Stat s (nolock) "
+ " LEFT OUTER JOIN tblPay#StatConfig c (nolock) ON s.configId = c.id "
+ " LEFT OUTER JOIN tblpay#StatSlot l (nolock) ON s.slotId = l.id "
+ " LEFT OUTER JOIN tblpay#company cm (nolock) ON s.networkId = cm.RecID "
+ " WHERE IntervalStartTime >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) "
+ " AND IntervalEndTime <= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) "
+ " AND s.configId = " + configID
+ " AND s.networkId = " + retailID
+ " GROUP BY cm.Name,IntervalStartTime,value) "
+ " SELECT Network,SUM(Value) AS Value, DAY,MONTH,YEAR,Type "
+ " FROM CTE "
+ " GROUP BY Network,DAY,Type,MONTH,YEAR "
+ " ORDER BY Network,Type ";
}else if(retailID.equals("999")){
sql = "WITH CTE AS("
+ " SELECT cm.Name AS Biller,Value,DAY(IntervalStartTime) AS DAY,MONTH(IntervalStartTime) AS MONTH,YEAR(IntervalStartTime) AS YEAR, "
+ " CASE WHEN MONTH(IntervalStartTime) = MONTH(GETDATE()) THEN 'Current' ELSE 'Previous' END AS Type "
+ " FROM tblpay#Stat s (nolock) "
+ " LEFT OUTER JOIN tblPay#StatConfig c (nolock) ON s.configId = c.id "
+ " LEFT OUTER JOIN tblpay#StatSlot l (nolock) ON s.slotId = l.id "
+ " LEFT OUTER JOIN tblpay#company cm (nolock) ON s.issuerId = cm.RecID "
+ " WHERE IntervalStartTime >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) "
+ " AND IntervalEndTime <= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) "
+ " AND s.configId = " + configID
+ " AND s.networkId = " + retailID
+ " GROUP BY cm.Name,IntervalStartTime,value) "
+ " SELECT Biller,SUM(Value) AS Value, DAY,MONTH,YEAR,Type "
+ " FROM CTE "
+ " GROUP BY Biller,DAY,Type,MONTH,YEAR "
+ " ORDER BY Biller,Type ";
}else{
sql = " WITH CTE AS( "
+ " SELECT cm.Name AS Network,co.Name AS Biller,DAY(IntervalStartTime) AS DAY,MONTH(IntervalStartTime) AS MONTH,YEAR(IntervalStartTime) AS YEAR, "
+ " CASE WHEN MONTH(IntervalStartTime) = MONTH(GETDATE()) THEN 'Current' ELSE 'Previous' END AS Type "
+ " FROM tblpay#Stat s (nolock) "
+ " LEFT OUTER JOIN tblPay#StatConfig c (nolock) ON s.configId = c.id "
+ " LEFT OUTER JOIN tblpay#StatSlot l (nolock) ON s.slotId = l.id "
+ " LEFT OUTER JOIN tblpay#company cm (nolock) ON s.networkId = cm.RecID "
+ " LEFT OUTER JOIN tblpay#company co (nolock) ON s.issuerId = co.RecID "
+ " WHERE IntervalStartTime >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE())-1, 0) "
+ " AND IntervalEndTime <= DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())+1,0)) "
+ " AND s.configId = " + configID
+ " AND s.networkId = " + retailID
+ " AND s.issuerId = " + billerID
+ " GROUP BY IntervalStartTime,cm.Name,value,co.Name) "
+ " SELECT Network,Biller, SUM(Value) AS Value,DAY,MONTH,YEAR,Type "
+ " FROM CTE "
+ " GROUP BY Network,DAY,MONTH,YEAR,Type,Biller "
+ " ORDER BY Network,Type ";
}
try {
Connection con = db.getDBConnection(DatabaseTypes.TRANSACTION_DATABASE);
ResultSet rs = DatabaseHandler.executeQuery(con, sql);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
maxTransactions = 0;
maxDays = 31;
boolean isEmpty = !rs.first();
if (!isEmpty) {
monthTotalsPrevious = new ArrayList<MonthlyGraphs>();
monthTotalsCurrent = new ArrayList<MonthlyGraphs>();
}
rs.beforeFirst();
while (rs.next()) {
MonthlyGraphs t = new MonthlyGraphs();
Calendar cal2 = Calendar.getInstance();
cal2.set(rs.getInt("YEAR"), rs.getInt("MONTH") - 1, rs.getInt("DAY"));
t.setDate(dateFormat.format(cal2.getTime()));
t.setTotalTransactions(rs.getInt("Value"));
t.setDay(rs.getInt("DAY"));
if (rs.getString("Type").equals("Current")) {
monthTotalsCurrent.add(t);
} else {
monthTotalsPrevious.add(t);
}
if (t.getTotalTransactions() > maxTransactions) {
maxTransactions = t.getTotalTransactions();
}
}
rs.close();
con.close();
createCategoryModel();
} catch (Exception e) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "An error occurred.", e.getMessage()));
}
}
private void createCategoryModel() {
chartModel = new CartesianChartModel();
ChartSeries dailyTotalsPrevious = new ChartSeries();
dailyTotalsPrevious.setLabel("Previous");
for (int i = 0; i < monthTotalsPrevious.size(); i++) {
dailyTotalsPrevious.set(monthTotalsPrevious.get(i).getDay(), monthTotalsPrevious.get(i).getTotalTransactions());
}
chartModel.addSeries(dailyTotalsPrevious);
ChartSeries dailyTotalsCurrent = new ChartSeries();
dailyTotalsCurrent.setLabel("Current");
for (int i = 0; i < monthTotalsCurrent.size(); i++) {
dailyTotalsCurrent.set(monthTotalsCurrent.get(i).getDay(), monthTotalsCurrent.get(i).getTotalTransactions());
}
chartModel.addSeries(dailyTotalsCurrent);
}
xhtml page:
<p:toolbar id ="graphtool">
<p:toolbarGroup align="left">
<h:panelGrid columns="6" cellpadding="5" >
<p:selectOneMenu id="billIssuerSelect" value="#{graphsBean.billerID}" style="width:250px" >
<f:selectItems value="#{generalBean.billIssuerList}" var="b" itemValue="#{b.billIssuerId}" itemLabel="#{b.billIssuerName}"/>
</p:selectOneMenu>
<p:selectOneMenu id="retailerSelect" value="#{graphsBean.retailID}" style="width: 250px" >
<f:selectItems value="#{generalBean.retailerList}" var="r" itemValue="#{r.retailerId}" itemLabel="#{r.retailerName}" />
</p:selectOneMenu>
<p:selectOneMenu id="configSelect" value="#{graphsBean.configID}" style="width: 250px" >
<f:selectItems value="#{graphsBean.configList}" var="r" itemValue="#{r.ID}" itemLabel="#{r.configName}" />
</p:selectOneMenu>
<p:commandButton id="refreshButton"
value="Generate"
icon="ui-icon-refresh"
update="graph"
ajax="true"
global="false"
actionListener="#{graphsBean.searchMonthTotals()}"/>
</h:panelGrid>
</p:toolbarGroup>
<p:toolbarGroup align="right">
<h:panelGrid columns="2" cellpadding="8" >
<h:commandLink>
<p:graphicImage style="border: none" value="../resources/excel24.png" />
<p:dataExporter type="xls" target="graph" fileName="Month Graph" />
</h:commandLink>
</h:panelGrid>
</p:toolbarGroup>
</p:toolbar>
<p:spacer width="10" height="10" />
<p:panel header="Month Graph">
<p:lineChart id="graph" value="#{graphsBean.chartModel}" style="width:500px;height:300px"
minY="0" maxY="#{graphsBean.maxTransactions}"
minX="1" maxX="#{graphsBean.maxDays}"
showMarkers="false"
legendPosition="n"
extender="customExtender"/>
</p:panel>
If anyone can guide me in the correct direction that would be great.
Thanks
I resolved the issue, there was a Javascript code in the xhtml page that needed to be included to generate the graph.
Related
Simplify Boolean Expression: X + X'Y'Z
I know that the following is equal: X + X'Y'Z = X + Y'Z How can simplify the left side to arrive the right side using basic Boolean identities? Thanks in advance.
Expression Justification --------------------------------- ------------------------- X + X'Y'Z initial expression (XY'Z + X(Y'Z)') + X'Y'Z r = rs + rs' (XY'Z + XY'Z + X(Y'Z)') + X'Y'Z r = r + r (XY'Z + X(Y'Z)' + XY'Z) + X'Y'Z r + s = s + r (XY'Z + X(Y'Z)') + (XY'Z + X'Y'Z) (r + s) + t = r + (s + t) X(Y'Z + (Y'Z)') + (Y'Z)(X + X') rs + rt = r(s + t) X(1) + (Y'Z)(1) r + r' = 1 X + Y'Z r(1) = r
The fastest way to prove this expression is to add a redundant term that will discard X' X + X'Y'Z = X(1+Y'Z) + X'Y'Z = X + XY'Z + X'Y'Z = X + (X+X')Y'Z = X + Y'Z
JPA, nativeQuery The value is shown above
The code below is repository #Query ( value = "select min(id) as id, coalesce (sum(case when points > 0 then points end), 0) as points, userid" + " from books" + " where userid = ?1" + " group by userid", nativeQuery = true ) JamInfo findPlus(Long userid); #Query ( value = "select min(id) as id, coalesce(sum(case when points < 0 then points*-1 end),0)as points, userid" + " from books" + " where userid = ?1" + " group by userid", nativeQuery = true ) JamInfo findMinus(Long userid); The code below is controller JamInfo jamplus = jamInfoRepository.findPlus(id); JamInfo jamminus = jamInfoRepository.findMinus(id); model.addAttribute("jamplus", jamplus); model.addAttribute("jamminus", jamminus); If you print it like this, it will be unified with the value of jamplus written first. How can the two values be output differently?
mysql average of best three
I have pieced this together from sites online and it works but not completely, what i need it to do is take the top 3 results and average them but it takes ALL results, can anyone point me in the right direction? SELECT i.NAME, e.comp, Round(Avg(c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5 + c.phase6), 2) AS "Average Score", ( CASE WHEN compID = '7' THEN Concat(Round(Avg( ( ( c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5 + c.phase6 ) / 400 ) * 100), 2), ' %') WHEN compID = '5' THEN Concat(Round(Avg( ( ( c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5 + c.phase6 ) / 600 ) * 100), 2), ' %') WHEN compID = '3' THEN Concat(Round(Avg(( ( c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5 + c.phase6 ) / 600 ) * 100), 2), ' %') ELSE 'Unspecified' END ) AS "Average as Percent" FROM jos_practicedetail c, jos_comps e, jos_practice g, jos_members i WHERE e.compsid = g.competition AND g.practiceid = c.practicepid AND i.memberid = c.competitorid AND g.typeID = '2' AND Year(g.pdate) = '2017' AND (SELECT Count(*) FROM jos_practicedetail b WHERE b.competitorid = c.competitorid AND b.practicepid = c.practicepid AND ( b.phase1 + b.phase2 + b.phase3 + b.phase4 + b.phase5 + b.phase6 ) >= ( c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5 + c.phase6 )) <= 3 GROUP BY competitorid HAVING Count(*) > 2 ORDER BY competitorid, ( Avg(c.phase1 + c.phase2 + c.phase3 + c.phase4 + c.phase5 + c.phase6) ) DESC
MySQL - How to use Left and Right Joins to get the result
I know the values for aw_id, ad_id and grp_id (e.g., aw_id = 5, ad_id = 46 and grp_id =2). I want to display all the at_cub_details where: at_cub_details.grp_id = 2 AND at_cub_details.cd_id = at_cub_awards.cd_id AND at_cub_awards.aw_id = 5 AND at_cub_awards.ca_awarded_date IS NULL OR at_cub_details.cd_id = at_cub_awards.cd_id AND at_cub_awards.aw_id = 5 does not exist Where at_cub_details.cd_id = at_cub_awards.cd_id AND at_cub_awards.aw_id = 5 AND at_cub_awards.ca_awarded_date = NULL does exist **then** at_cub_awards.ca_id = at_cub_award_date.ca_id AND at_cub_award_date.ad_id = 46 AND at_cub_award_date.cad_task_completion_date IS NULL OR at_cub_awards.ca_id = at_cub_award_date.ca_id AND at_cub_award_date.ad_id = 46 does not exist I have have tried all manner of RIGHT and LEFT joins on this without any luck.
The solution was: String selectQry = ("SELECT * from ( " + "SELECT DISTINCT at_cub_details.cd_id as cdid, " + "at_cub_details.grp_id as grpid, " + "at_cub_details.cd_surname as surname, " + "at_cub_details.cd_first_name as firstName, " + "at_cub_details.cd_dob as dob, " + "at_cub_details.cd_photograph as photograph, " + "at_cub_details.cd_archived as archived, " + "at_cub_details.cd_scout_no as scoutNo " + "FROM at_account_group, at_cub_details " + "LEFT JOIN at_cub_awards ON (at_cub_details.cd_id = at_cub_awards.cd_id AND at_cub_awards.aw_id = ?) " + "WHERE at_cub_awards.cd_id IS NULL " + "AND at_cub_details.grp_id = at_account_group.grp_id " + "AND at_account_group.acc_id = ? " + "UNION " + "SELECT DISTINCT at_cub_details.cd_id as cdid, " + "at_cub_details.grp_id as grpid, " + "at_cub_details.cd_surname as surname, " + "at_cub_details.cd_first_name as firstName, " + "at_cub_details.cd_dob as dob, " + "at_cub_details.cd_photograph as photograph, " + "at_cub_details.cd_archived as archived, " + "at_cub_details.cd_scout_no as scoutNo " + "FROM at_account_group, at_cub_details, at_cub_awards, at_cub_award_date " + "WHERE at_cub_details.grp_id = at_account_group.grp_id " + "AND at_account_group.acc_id = ? " + "AND at_cub_awards.cd_id = at_cub_details.cd_id " + "AND (at_cub_awards.aw_id = ? AND at_cub_awards.ca_awarded_date IS NULL) " + "AND (at_cub_awards.ca_id = at_cub_award_date. ca_id " + "AND at_cub_award_date.cad_task_completion_date IS NULL " + "AND at_cub_award_date.ad_id = ?) " + "UNION " + "SELECT DISTINCT at_cub_details.cd_id as cdid, " + "at_cub_details.grp_id as grpid, " + "at_cub_details.cd_surname as surname, " + "at_cub_details.cd_first_name as firstName, " + "at_cub_details.cd_dob as dob, " + "at_cub_details.cd_photograph as photograph, " + "at_cub_details.cd_archived as archived, " + "at_cub_details.cd_scout_no as scoutNo " + "FROM at_account_group, at_cub_details, at_cub_awards " + "LEFT JOIN at_cub_award_date ON (at_cub_awards.ca_id = at_cub_award_date.ca_id) " + "WHERE at_cub_award_date.ca_id IS NULL " + "AND at_cub_awards.ca_awarded_date IS NULL AND at_cub_awards.aw_id = ? " + "AND at_cub_details.grp_id = at_account_group.grp_id " + "AND at_account_group.acc_id = ? " + "AND at_cub_awards.cd_id = at_cub_details.cd_id " + " ) a " + "ORDER BY surname, firstName;");
HibernateException: Errors in named queries: FindPostWithComments
In my Spring 4 application I have an issue with named native query: #NamedNativeQuery(name = "FindPostWithComments", query = " SELECT * FROM (" + " SELECT p.*, " + " MATCH (description) AGAINST ('text') AS score " + " FROM posts as p" + " WHERE MATCH (description) AGAINST ('text') > 0 " + " LIMIT 0, 10 " + " ) p LEFT JOIN ( " + " SELECT c.*, " + " #rownumber := CASE WHEN #post_id = post_id THEN #rownumber + 1 ELSE 1 END AS n, " + " #post_id := post_id " + " FROM comments c, " + " (SELECT #rownumber := 0, #post_id := 0) r " + " WHERE MATCH (content) AGAINST ('text') > 0 " + " ORDER BY c.last_edited DESC, post_id DESC " + " ) c ON p.post_id = c.post_id " + " WHERE c.post_id IS NULL OR n BETWEEN 1 and 3 " + " ORDER BY score DESC " , resultSetMapping = "PostWithComments") #SqlResultSetMappings({ #SqlResultSetMapping( name = "PostWithComments", entities = { #EntityResult(entityClass = Post.class, fields = { #FieldResult(name = "id", column = "p.post_id"), #FieldResult(name = "userId", column = "p.user_id"), #FieldResult(name = "type", column = "p.type_id"), #FieldResult(name = "description", column = "p.description"), #FieldResult(name = "link", column = "p.link"), #FieldResult(name = "dateCreated", column = "p.date_created"), #FieldResult(name = "lastEdited", column = "p.last_edited"), #FieldResult(name = "totalVotes", column = "p.total_votes"), #FieldResult(name = "totalComments", column = "p.total_comments") } ), #EntityResult(entityClass = Comment.class, fields = { #FieldResult(name = "id", column = "c.comment_id"), #FieldResult(name = "post", column = "c.post_id"), #FieldResult(name = "userId", column = "c.user_id"), #FieldResult(name = "dateCreated", column = "c.date_created"), #FieldResult(name = "lastEdited", column = "c.last_edited"), #FieldResult(name = "content", column = "c.content"), #FieldResult(name = "totalVotes", column = "c.total_votes") } ) } ) }) It fails during the application startup with a following exception: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Errors in named queries: FindPostWithComments at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1566) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4728) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5162) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.hibernate.HibernateException: Errors in named queries: FindPostWithComments at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:545) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1859) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:845) at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398) at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:844) at org.hibernate.jpa.HibernatePersistenceProvider.createContainerEntityManagerFactory(HibernatePersistenceProvider.java:152) at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:338) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562) ... 21 more What is the possible cause? This query perfectly works from MySQL workbench.
I found the reason by myself. I need to add double slashes before each colon sign, so the final query must look like: " SELECT * FROM (" + " SELECT p.*, " + " MATCH (description) AGAINST (:term) AS score " + " FROM posts as p" + " WHERE MATCH (description) AGAINST (:term) > 0 " + " LIMIT 0, 10 " + " ) p LEFT JOIN ( " + " SELECT c.*, " + " #rownumber \\:= CASE WHEN #post_id = post_id THEN #rownumber + 1 ELSE 1 END AS n, " + " #post_id \\:= post_id " + " FROM comments c, " + " (SELECT #rownumber \\:= 0, #post_id \\:= 0) r " + " WHERE MATCH (content) AGAINST (:term) > 0 " + " ORDER BY c.last_edited DESC, post_id DESC " + " ) c ON p.post_id = c.post_id " + " WHERE c.post_id IS NULL OR n BETWEEN 1 and 3 " + " ORDER BY score DESC "