php mysql multi-table sub-query of queries

The so-called sub-query is the first to check out a result by means of a statement, and then by the results of a query from the query again. Subquery generally have the following three kinds. Here to do a case to explain.

Case: check the latest product information that one under each classification in [Example 1].

If the query by a single sentence, is to get reach. As follows is wrong:

select max(goods_id),cat_id,goods_name from goods group by cat_id;

So to get the latest product ID number goods_id each category, but other information such as product name goods_name that one is old. Therefore, in order to obtain the latest information on each category of merchandise, either separate statement to query or sub-query.

1: where subquery.

select * from goods where goods_id in ( select max(goods_id) from goods group by cat_id);

This code, we first check out the latest with a group by product ID for each category, and then where ... in () conditional statement check out the latest merchandise ID to each category of information goods. Here is the group by statement as a child where the query.

2: from sub-query.

select * from (select * from goods order by cat_id,goods_id desc) as gk group by cat_id;

From the sub-query is to select as a result of the query to a table, such as bold above the code. Note: you must select the query result set to an alias, such as the red part of the code above. Otherwise it will error.

In this way, we also check out the latest information under each category of merchandise.

3: exists subquery:

Topic: Query commodity under which section [Example 1]. Catalog name: category

select * from category where exists( select * from goods where goods.cat_id=category.cat_id )

上句中的exists排查了(当商品表中的分类ID=分类表中的分类ID)时,有没有商品。如果有,就再查询这个分类的信息,如查没有,就排除这个分类。最后结果就是,查询出了有商品的商品分类信息。

嗯,这里我们介绍了3种比较常用的mysql数据库子查询语句:where子查询语句、from子查询语句、exists子查询语句。当然,如果你不想使用子查询语句,也可以把它们拆分成2个语句来执行,效果也是一样的。

 

转载:http://wanlimm.com/77201808176609.html

Guess you like

Origin www.cnblogs.com/beijinglaolei/p/11716501.html
Recommended