MySQL select from where multiple conditions

本文深入讲解了MySQL中SELECT语句的高级用法,包括如何使用WHERE子句限制查询条件,通过AND与OR组合多个条件,以及如何利用括号进行条件分组以精确匹配需求。文章通过具体示例展示了如何查询特定年龄段的男性名字,以及如何获取特定姓氏的年轻人数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Maybe one of the most used MySQL commands is SELECT, that is the way to stract the information from the database, but of course one does not need all the info inside a database, therefore one should limit the info coming out from the table, there is WHERE statement comes into play, with it one can limit the data to only the one that complies with certain condition. What if that is still too wide?. Then it can be used multiple conditions. Here some options:

Working with two conditions

Using AND with two or more conditions the query can be narrowed to meet your needs.

SELECT * FROM table WHERE column1 = 'var1' AND column2 = 'var2';

Only when the two conditions are met the row is stracted from the database's table. What if any of them should be met to get the data?

SELECT * FROM table WHERE column1 = 'var1' OR column2 = 'var2';

Using OR will tell MySQL to return data if one or both conditions are met.

Working with more than two conditions

If more than two conditions need to be met in order to show a result, you need to use parenthesis and nest the conditions according to your needs. This time it will be easier with examples.

Consider this table:

+------------+-----------+--------+-----+
| fname      | lname     | gender | age |
+------------+-----------+--------+-----+
| John       | Smith     | M      | 30  |
+------------+-----------+--------+-----+
| Jane       | Doe       | F      | 20  |
+------------+-----------+--------+-----+
| Richard    | Stallman  | M      | 70  |
+------------+-----------+--------+-----+
| John       | Doe       | M      | 20  |
+------------+-----------+--------+-----+

If you want to get all young male's names use this query.

SELECT * FROM table WHERE gender = M AND age >=  '18' AND age <= '50';

If you want to get all young people with last name Doe or Smith, use this query.

SELECT * FROM table WHERE age >= '18' AND age <= '50' AND (lname = 'Doe' OR lname = 'Smith');

As you can see we are using parenthesis to get a result from last names, because you want one or the other, then you use AND to get the age range and finally an AND to join the results from age range and the results from names.

SELECT unique_id,COUNT(unique_id) FROM yourtblname GROUP BY unique_id HAVING COUNT(unique_id) >1

转载于:https://www.cnblogs.com/kzwrcom/p/11592430.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值