mysql筛选条件,求高手
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql筛选条件,求高手相关的知识,希望对你有一定的参考价值。
如图,该表部分数据
我要进行一个筛选。
1、比如我要取得标签为92的相册id,则得到结果的相册id有78,115,116
2、现在我又添加一个筛选条件,即在上一个筛选条件上增加取得标签为96这条件,那么取出的相册id有115和116,78就被排除了
这如何操作才好?似乎很麻烦啊,能否给个思路。
我目前想的是在上一次查询结果中再查询,但这怎么做到?或者有何其他更好的方法?
2)$sql="select group_concat(infoid),tagid from tab where tagid in (92,96) group by tagid"; 参考技术A $的SQL?=“选择*从房子里house_price>'$ cdayprice'和定位='东城区' 参考技术B 逻辑似乎不太对吧,条件都是标签id,怎么分两次查询呢追问
不是光写成一条sql语句,估计写成一条是查不出来的。
我通过第一次筛选设定一个标签id,查询出来之后,我还要通过php语言组织下一个条件,再进行查询
MySQL数据库,内连接外连接中做条件筛选和WHERE中条件筛选的区别
最近写数据库SQL做连接、条件筛选数据操作时发现了一个问题,就是两张表在做等值连接、或者外连接时用AND对连接表数据进行筛选和最后用WHERE对结果集数据表进行筛选得到的查询结果是有区别的。
先来个简单例子看下,在对结果进行具体分析。
1.外连接
ON后用AND对连接表数据进行筛选
WITH table_1 AS(
SELECT 'a1' AS id_1, 'b1' AS id_2, 'name_1' AS name_1
UNION ALL
SELECT 'a2' AS id_1, 'b2' AS id_2, 'name_2' AS name_1
UNION ALL
SELECT 'a3' AS id_1, 'b3' AS id_2, 'name_3' AS name_1
UNION ALL
SELECT 'a4' AS id_1, 'b1' AS id_2, 'name_4' AS name_1
),
table_2 AS(
SELECT 'b1' AS id_2, 'aa' AS name_2
UNION ALL
SELECT 'b2' AS id_2, 'bb' AS name_2
)
SELECT
*
FROM
table_1
LEFT OUTER JOIN table_2
ON table_1.id_2 = table_2.id_2
AND table_2.name_2 = 'aa'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
结果
修改成WHERE对结果数据集筛选
WITH table_1 AS(
SELECT 'a1' AS id_1, 'b1' AS id_2, 'name_1' AS name_1
UNION ALL
SELECT 'a2' AS id_1, 'b2' AS id_2, 'name_2' AS name_1
UNION ALL
SELECT 'a3' AS id_1, 'b3' AS id_2, 'name_3' AS name_1
UNION ALL
SELECT 'a4' AS id_1, 'b1' AS id_2, 'name_4' AS name_1
),
table_2 AS(
SELECT 'b1' AS id_2, 'aa' AS name_2
UNION ALL
SELECT 'b2' AS id_2, 'bb' AS name_2
)
SELECT
*
FROM
table_1
LEFT OUTER JOIN table_2
ON table_1.id_2 = table_2.id_2
WHERE table_2.name_2 = 'aa'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
结果
2.等值连接
ON后用AND对连接表数据进行筛选
WITH table_1 AS(
SELECT 'a1' AS id_1, 'b1' AS id_2, 'name_1' AS name_1
UNION ALL
SELECT 'a2' AS id_1, 'b2' AS id_2, 'name_2' AS name_1
UNION ALL
SELECT 'a3' AS id_1, 'b3' AS id_2, 'name_3' AS name_1
UNION ALL
SELECT 'a4' AS id_1, 'b1' AS id_2, 'name_4' AS name_1
),
table_2 AS(
SELECT 'b1' AS id_2, 'aa' AS name_2
UNION ALL
SELECT 'b2' AS id_2, 'bb' AS name_2
)
SELECT
*
FROM
table_1
INNER JOIN table_2
ON table_1.id_2 = table_2.id_2
AND table_2.name_2 = 'aa'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
结果
修改成WHERE对结果数据集筛选
WITH table_1 AS(
SELECT 'a1' AS id_1, 'b1' AS id_2, 'name_1' AS name_1
UNION ALL
SELECT 'a2' AS id_1, 'b2' AS id_2, 'name_2' AS name_1
UNION ALL
SELECT 'a3' AS id_1, 'b3' AS id_2, 'name_3' AS name_1
UNION ALL
SELECT 'a4' AS id_1, 'b1' AS id_2, 'name_4' AS name_1
),
table_2 AS(
SELECT 'b1' AS id_2, 'aa' AS name_2
UNION ALL
SELECT 'b2' AS id_2, 'bb' AS name_2
)
SELECT
*
FROM
table_1
INNER JOIN table_2
ON table_1.id_2 = table_2.id_2
WHERE table_2.name_2 = 'aa'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
结果
原理:在等值连接、外连接ON后用AND做条件筛选数据时,是先对连接表的数据进行条件筛选,筛选后和被连接表进行相应连接,而WHERE是对结果集进行筛选,先连接后筛选数据。
以上是关于mysql筛选条件,求高手的主要内容,如果未能解决你的问题,请参考以下文章