假设有个表 k 字段如下
kid ktag
1 aaa1
2 bbb1
3 bbb2
4 aaa2
5 ccc1
6 aaa3
7 ccc2
8 ddd1
9 aaa4我想要搜索 ktag 中包含 aaa 和 bbb 的结果 ,而且符合条件的只要一条结果 怎么搜?select * from k where (ktag like '%aaa%' ) or (ktag like '%bbb%' )
搜索出来的 aaa 相关和 bbb 相关的结果都不止一条而且搜索出来的 最好是符合条件的最新的结果 也就是kid 最大的结果
kid ktag
1 aaa1
2 bbb1
3 bbb2
4 aaa2
5 ccc1
6 aaa3
7 ccc2
8 ddd1
9 aaa4我想要搜索 ktag 中包含 aaa 和 bbb 的结果 ,而且符合条件的只要一条结果 怎么搜?select * from k where (ktag like '%aaa%' ) or (ktag like '%bbb%' )
搜索出来的 aaa 相关和 bbb 相关的结果都不止一条而且搜索出来的 最好是符合条件的最新的结果 也就是kid 最大的结果
(ktag like 'bbb%' and not exists(select 1 from k where a.kid<kid and ktag like 'bbb%'))
or
(ktag like 'aaa%' and not exists(select 1 from k where a.kid<kid and ktag like 'aaa%'))
意思看明白了
但是
select 1 from ……
是不是错了 是limit 1的意思?
不行么?
你这就出一条结果 完全不合期望
就是我最开始写的加了个limit嘛
mysql> select * from t_ycnxz;
+------+------+
| kid | ktag |
+------+------+
| 1 | aaa1 |
| 2 | bbb1 |
| 3 | bbb2 |
| 4 | aaa2 |
| 5 | ccc1 |
| 6 | aaa3 |
| 7 | ccc2 |
| 8 | ddd1 |
| 9 | aaa4 |
+------+------+
9 rows in set (0.00 sec)mysql> select * from k where (ktag like '%aaa%' ) or (ktag like '%bbb%' ) ;
ERROR 1146 (42S02): Table 'csdn.k' doesn't exist
mysql> select * from t_ycnxz where (ktag like '%aaa%' ) or (ktag like '%bbb%' )
;
+------+------+
| kid | ktag |
+------+------+
| 1 | aaa1 |
| 2 | bbb1 |
| 3 | bbb2 |
| 4 | aaa2 |
| 6 | aaa3 |
| 9 | aaa4 |
+------+------+
6 rows in set (0.15 sec)mysql> select * from t_ycnxz where (ktag like '%aaa%' ) or (ktag like '%bbb%' )
order by kid desc limit 1;
+------+------+
| kid | ktag |
+------+------+
| 9 | aaa4 |
+------+------+
1 row in set (0.01 sec)mysql>
我是要 aaa 的只出一条 bbb的只出一条,在2楼启发下已经找到方法了,贴在3楼。
-> (ktag like 'bbb%' and not exists(select 1 from k where a.kid<kid and ktag
like 'bbb%'))
-> or
-> (ktag like 'aaa%' and not exists(select 1 from k where a.kid<kid and ktag
like 'aaa%'));
+------+------+
| kid | ktag |
+------+------+
| 3 | bbb2 |
| 9 | aaa4 |
+------+------+
2 rows in set (0.00 sec)mysql>
问题说明越详细,回答也会越准确!参见如何提问。(提问的智慧)
mysql> (select * from t_ycnxz where ktag like '%aaa%' order by kid desc limit 1)
-> union all
-> (select * from t_ycnxz where ktag like '%bbb%' order by kid desc limit 1);
+------+------+
| kid | ktag |
+------+------+
| 9 | aaa4 |
| 3 | bbb2 |
+------+------+
2 rows in set (0.04 sec)mysql>
建议你列出你的表结构,并提供测试数据以及基于这些测试数据的所对应正确结果。
参考一下这个贴子的提问方式http://topic.csdn.net/u/20091130/20/8343ee6a-417c-4c2d-9415-fa46604a00cf.html
1. 你的 create table xxx .. 语句
2. 你的 insert into xxx ... 语句
3. 结果是什么样,(并给以简单的算法描述)
4. 你用的数据库名称和版本(经常有人在MS SQL server版问 MySQL)
这样想帮你的人可以直接搭建和你相同的环境,并在给出方案前进行测试,避免文字描述理解上的误差。