sql从同一表里查询多条不同条件的数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql从同一表里查询多条不同条件的数据相关的知识,希望对你有一定的参考价值。

请问如何一次从表“A”查询三个数据:
1. a_id, a_title, a_name 条件:a_id=10
2. top 1 a_id, a_title 条件:a_id>10
3. top 1 a_id, a_title 条件:a_id<10
请教完整的查询语句,谢谢!
如果用以下语句:
select a_id, a_title, a_name from A where a_id=10
union all
select top 1 a_id, a_title, a_name from A where a_id>10
union all
select top 1 a_id, a_title, a_name from A where a_id<10
会出现:“关键字‘union’附近有语法错误!”
SELECT a_id, a_title, a_name
FROM A AS a
WHERE (l_id = 10)
UNION ALL
SELECT TOP (1) a_name
FROM A AS b
WHERE (a_id > 10)
UNION ALL
SELECT TOP (1) a_name
FROM A AS c
WHERE (a_id < 10)
以上语句可以查到三条记录,但却是1、10、11,而不是我希望得到的9、10、11,请问ORDER BY要如何加入呢?

SELECT a_id, a_title, a_name
FROM A AS a
WHERE (l_id = 10)
UNION ALL
SELECT TOP (1) a_name
FROM A AS b
WHERE (a_id > 10)
UNION ALL
SELECT TOP (1) a_name
FROM A AS c
WHERE (a_id < 10)
如果是要这样查询要如何改呢?希望得到a_id=9、10、11的记录(在目标列表中有不同数目的表达式)

union all 我觉得不是一个好的方法,第一:它必须相同数目,也就是如果第一条查询a_id,a_title,a_name以下几条查询也要同时查这三个项目,第二:它返回了三条数据,而我是希望能返回一条数据在几个列上。

参考技术A 试试:
select
a_id,
a_title,
a_name
from
A
where
a_id=10
union
all
select
*
from
(
select
top
1
a_id,
a_title,
a_name
from
A
where
a_id<10
order
by
a_id
desc)
union
all
select
top
1
a_id,
a_title,
a_name
from
A
where
a_id>10
参考技术B select a_id, a_title, a_name from A a where a.a_id=10
union all
select top 1 a_id, a_title, a_name from A b where b.a_id>10
union all
select top 1 a_id, a_title, a_name from A c where c.a_id<10
参考技术C SELECT a_id, a_title, a_name
FROM A AS a
WHERE (l_id = 10)
UNION ALL
SELECT TOP (1) a_name
FROM A AS b
WHERE (a_id > 10) order by a_id asc
UNION ALL
SELECT TOP (1) a_name
FROM A AS c
WHERE (a_id < 10) order by a_id desc
参考技术D 试试:
select a_id, a_title, a_name from A where a_id=10
union all
select * from (
select top 1 a_id, a_title, a_name from A where a_id<10 order by a_id desc)
union all
select top 1 a_id, a_title, a_name from A where a_id>10本回答被提问者采纳
第5个回答  2010-06-02 你的语法不会错啦,有可能是你的数据类型我一致,导致没有被识别,建议查看,还有就是符号问题,你给出来的语句是正确的哟!你自己检查一下!

mysql:只用一条sql语句,如何查出一个表里,不同条件对应的数据条数

如下表:

id name age sex
1 a 1 0
2 b 10 1
3 c 2 1

得出:sex为1且age为2的数量,sex为1且age为5的数量,sex为1且age为10的数量
要求:效率高
可能我表达的不是很清楚,需要得出的是sex为1的情况下,有多少个是2岁,多少个是5岁,多少个是10岁这三个答案

mysql只用一条sql语句查出一个表里不同条件对应的数据条数的步骤如下:

我们需要准备的材料分别是:电脑、sql查询器。

1、首先,打开sql查询器,连接上相应的数据库表,例如stu2表。

2、点击“查询”按钮,输入:

select count(*) from stu2 where sex=1 and age=2

union all

select count(*) from stu2 where sex=1 and age=5

union all

select count(*) from stu2 where sex=1 and age=10

3、点击“运行”按钮,此时能只通过一条sql高效查询结果。

参考技术A

看一下这个SQL

select
sum(
if((sex = 1 and age = 2),1,0)
),
sum(
if((sex = 1 and age = 5),1,0)
),
sum(
if((sex = 1 and age = 10),1,0)
)
from a_test

 这个SQL现在就是得出的这个结果

本回答被提问者和网友采纳

以上是关于sql从同一表里查询多条不同条件的数据的主要内容,如果未能解决你的问题,请参考以下文章

将多条查询结果作为like查询条件

SQL如何将一个表里的不同条件查询结果拼接显示

mysql:只用一条sql语句,如何查出一个表里,不同条件对应的数据条数

SQL一次性查询一个字段不同条件下的统计结果

PL/SQL-表和条件都不同时如何在单个查询中实现多条count语句

SQL一次性查询一个字段不同条件下的统计结果(另一张表的统计数量)