文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>mysql_tips

mysql_tips

时间:2007-02-17  来源:PHP爱好者

1 TIP1
------

状态说明
--------

以下建立一个demo表和一些数据, 其中pid为产品编号, sid为分类编号
查询目的是为了查询属于不同分类的所有产品.

注意: mysql 3.22以下版本不支持子查询, 但所有的子查询都可以使用
LEFT JOIN 或 and语句替代.

create table table1 (
pid char (10) not null ,
sid char (10) not null
);

insert into table1 values ("apple","1");
insert into table1 values ("apple","2");
insert into table1 values ("apple","3");
insert into table1 values ("apple","4");
insert into table1 values ("apple","5");
insert into table1 values ("apple","6");
insert into table1 values ("pear","1");
insert into table1 values ("pear","3");
insert into table1 values ("pear","4");
insert into table1 values ("pear","7");
insert into table1 values ("orange","1");
insert into table1 values ("orange","2");
insert into table1 values ("orange","3");

查询方法
--------

设定分类有3类, 我们希望查询这些分类中分属以下类型的产品:

sort 1 sort 2 sort 3
---------------------------
1 -- 3 -- ( 2 | 4 )

我们使用如下的SQL语句:

select t1.pid from table1 as t1
LEFT JOIN table1 as t2 on t1.pid=t2.pid
LEFT JOIN table1 as t3 on t1.pid=t3.pid
where t1.sid=1 and t2.sid=3 and (t3.sid=2 or t3.sid=4)
group by pid;

结果为:

+-------+
|t1.pid |
+-------+
|apple |
|pear |
|orange |
+-------+

如果希望查询分类如下:

sort 1 sort 2 sort 3
--------------------------------------
( 1 | 5 ) -- ( 3 | 6 | 7 ) -- 4

使用如下的SQL语句:

select t1.pid from table1 as t1
LEFT JOIN table1 as t2 on t1.pid=t2.pid
LEFT JOIN table1 as t3 on t1.pid=t3.pid
where ( t1.sid=1 or t1.sid=5 )
and (t2.sid=3 or t2.sid=6 or t2.sid=7)
and (t3.sid=2 or t3.sid=4)
group by pid;

结果为:

+------+
|t1.pid|
+------+
|apple |
|pear |
+------+

如果有更多的分类, 并且希望查询的分类如下:

sort 1 sort 2 sort 3 sort 4
--------------------------------------
( 1 ) -- ( 3 ) -- ( 2 | 4) -- ( 5 )

我们使用如下语句:

select t1.pid from table1 as t1
LEFT JOIN table1 as t2 on t1.pid=t2.pid
LEFT JOIN table1 as t3 on t1.pid=t3.pid
LEFT JOIN table1 as t4 on t1.pid=t4.pid
where t1.sid=1
and t2.sid=3
and (t3.sid=2 or t3.sid=4)
and t4.sid=5
group by pid;
结果为:

+------+
|t1.pid|
+------+
|apple |
+------+

整个SQL语句可以由程序生成.


非常全面的一个php技术网站,php 爱好者站 http://www.phpfans.net 有相当丰富的文章和源代码.
相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载