[技巧] mysql 3.22以下版本不支持子查询, 但所有的子查询都可以使用LEFT JOIN 或 and语句替代

shuixin13 2002-10-15 11:26:48
加精
以下建立一个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 |
+------+
...全文
185 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
男人三十好累 2002-12-02
  • 打赏
  • 举报
回复
mysql都出了这么多版本.还不支持子查询.看来免费就是免费.没办法.
Tomcat4 2002-10-17
  • 打赏
  • 举报
回复
up!
dejoy 2002-10-16
  • 打赏
  • 举报
回复
收藏,但 目前MySQL4.05 也不支持子查询的。
ATCG 2002-10-16
  • 打赏
  • 举报
回复
收藏,但 MySQL3.23 也不支持子查询的。
shuixin13 2002-10-16
  • 打赏
  • 举报
回复
呵呵,
是了,
至目前为止,
MySQL还不支持子查询,

等MySQL4.1了,希望有不凡表现!!

56,679

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧