Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain this SQL query to me?

Tags:

sql

php

explain

I'm reading this article and I'm trying to understand this SQL statement but I am still somewhat new to SQL.

I'm not sure what comment and c refer to.
I think one of them is the table name but I am not sure of the other. Also, apparently there is a subquery within it which I have not had any experience with:

  SELECT c.id, c.user_id, c.body, c.deep, c.lineage, c.parent_id,
         (SELECT COUNT(*) 
            FROM comment 
           WHERE comment.lineage LIKE (CONCAT(c.lineage,'%')) 
             AND comment.lineage != c.lineage) AS replies
    FROM comment as c
ORDER BY c.lineage
like image 925
John Smith Avatar asked Mar 13 '11 00:03

John Smith


People also ask

How do you explain what SQL is to someone without a technical background?

1. How do you explain what SQL is to someone without a technical background? SQL or Structured Query Language is a standardized programming language used to access or manipulate data in a database. It was designed to update, add, delete a row of data and retrieve subsets of information within the database.

What is query in SQL explain with example?

A query is a request for data or information from a database table or combination of tables. This data may be generated as results returned by Structured Query Language (SQL) or as pictorials, graphs or complex results, e.g., trend analyses from data-mining tools.


1 Answers

SELECT c.id,
       c.user_id,
       c.body, 
       c.deep, 
       c.lineage, 
       c.parent_id, (
       SELECT COUNT(*)
         FROM comment
        where comment.lineage LIKE (CONCAT(c.lineage,'%'))
          AND comment.lineage!=c.lineage)
       as replies
       FROM comment as c 
       order by c.linea

The first list are all the fields to be selected, with the prefix of c which is the alias later to the comment table.

The query in a query is a subquery, which runs that query which does a like and concatenates .clineage with % (which is the wildcard). This subquery result is saved in replies.

The results are ordered by linea.

like image 148
alex Avatar answered Sep 20 '22 18:09

alex