Note: 1. the nId value of the groupbya. nId field in the preceding two examples must be unique. It is best to have a unique index. 2. The first example seems to be more compatible.
Note: 1. the nId value of the group by a. nId field in the preceding two examples must be unique. It is best to have a unique index. 2. The first example seems to be more compatible.
A main table named "news" has the nId (auto-increment) and sName fields.
Record:
10 name10
13 name13
20 name20
21 name20
21 name20
30 name20
From the table reply, field nId (auto-increment), pId, sReply.
Record:
20 aaaaa
13 bbbbb
10 ccccccc
20 vvvvvv
20 hhhhhh
10 sssss
Associate the field pId with the nId of the primary table field from the table.
Objective: To obtain several records from the primary table. sort by: sort by the number of records associated with the primary table.
For example, the record sequence of the master table should be:
20 name20
10 name10
13 name13
Answer 1:
Select *, count (*) as iReply from
(SELECT a. nId, a. sName, B. sReply FROM news a, reply B WHERE a. nId = B. pId) as T
Group by nId order by iReply limit 0, 3
Answer 2:
SELECT a. nId, a. sName, count (B. sReply) as iReply from FROM news a, reply B WHERE a. nId = B. pId
Group by a. nId order by iReply limit 0, 3
Note:
1. In the above two examples, the value of the nId field such as group by a. nId should be unique. It is best to have a unique index.
2. The first example seems easier to understand, that is, to look up the table again from the results of the combined lookup table. The result of the combined lookup table is used as a "table" and then operated on it. Note that the syntax of the SQL statement here is worth learning.
3. A good solution is the second example.
4, but the biggest drawback of the above two examples is that the efficiency is too low! The Union lookup table is the Cartesian product of the most tables, and the number of queries is the product of the number of records of two tables. This is fatal for large table queries.
A good practice is to create a field in the master table to indicate the number of records in the slave table. The value of this field is modified at the same time each time a record is inserted or deleted into the slave table. To achieve the goal of the question, you only need to query the master table and sort the questions.
,