mysql查询语句

MySQL查询语句是用于从数据库中选择数据的基本工具,其基本语法结构如下:

SELECT column1, column2, ...
FROM table_name
[WHERE condition]
[GROUP BY column1, column2, ...]
[HAVING condition]
[ORDER BY column1 ASC|DESC]
[LIMIT M, N]
  1. 基础查询
  • 查询所有字段:SELECT * FROM table_name;

  • 查询指定字段:SELECT column1, column2 FROM table_name;

  • 使用 AS 给字段起别名:SELECT column1 AS alias1, column2 AS alias2 FROM table_name;

  1. 条件查询
  • 使用 WHERE 子句筛选数据:SELECT * FROM table_name WHERE condition;

  • 示例:SELECT name, age FROM user WHERE age > 18;

  • 逻辑运算符:AND, OR, NOT

  • 示例:SELECT * FROM student WHERE age >= 20 AND score > 50;

  1. 排序和限制
  • 使用 ORDER BY 对查询结果进行排序:SELECT * FROM table_name ORDER BY column_name ASC|DESC;

  • 示例:SELECT name, score FROM student ORDER BY score DESC LIMIT 3;

  1. 分组查询
  • 使用 GROUP BY 按指定列分组:SELECT column1, AVG(column2) FROM table_name GROUP BY column1;

  • 示例:SELECT class_id, AVG(score) AS avg_score FROM student GROUP BY class_id;

  1. 聚合函数
  • COUNT:SELECT COUNT(*) FROM table_name;

  • SUM:SELECT SUM(column_name) FROM table_name;

  • AVG:SELECT AVG(column_name) FROM table_name;

  • MAX:SELECT MAX(column_name) FROM table_name;

  • MIN:SELECT MIN(column_name) FROM table_name;

  1. 多表查询
  • 子查询:SELECT * FROM table1 WHERE column_name IN (SELECT column_name FROM table2);

  • 联表查询(JOIN):SELECT t1.column1, t2.column2 FROM table1 t1 INNER JOIN table2 t2 ON t1.column_name = t2.column_name;

  1. 其他
  • LIKE:用于模糊匹配,LIKE 'pattern%'

  • REGEXP:用于正则表达式匹配,REGEXP 'pattern'

示例

  1. 查询所有字段
    SELECT * FROM user;
    ```

2. **查询指定字段** <b class="card40_249__sup_a7f6" data-sup="sup">4</b>:

```sql
    SELECT name, age FROM user;
    ```

3. **使用 AS 起别名** :

```sql
    SELECT name AS user_name, age AS user_age FROM user;
    ```

4. **条件查询** :

```sql
    SELECT * FROM user WHERE age > 18;
    ```

5. **排序和限制** <b class="card40_249__sup_a7f6" data-sup="sup">5</b>:

```sql
    SELECT name, score FROM student ORDER BY score DESC LIMIT 3;
    ```

6. **分组查询** <b class="card40_249__sup_a7f6" data-sup="sup">4</b>:

```sql
    SELECT class_id, AVG(score) AS avg_score FROM student GROUP BY class_id;
    ```

7. **聚合函数** <b class="card40_249__sup_a7f6" data-sup="sup">5</b>:

```sql
    SELECT COUNT(*) FROM student;
    SELECT SUM(score) AS total_score FROM student;
    SELECT AVG(score) AS average_score FROM student;
    SELECT MAX(score) AS highest_score FROM student;
    SELECT MIN(score) AS lowest_score FROM student;
    ```

8. **多表查询 - 子查询** <b class="card40_249__sup_a7f6" data-sup="sup">4</b>:

```sql
    SELECT * FROM orders WHERE order_id IN (SELECT order_id FROM customers WHERE city = 'New York');
    ```

9. **多表查询 - 联表查询** <b class="card40_249__sup_a7f6" data-sup="sup">4</b>:

```sql
    SELECT customers.name, orders.order_date
    FROM customers
    INNER JOIN orders ON customers.customer_id = orders.customer_id;
    ```

这些查询语句可以帮助你高效地从MySQL数据库中检索所需的数据<b class="card40_249__sup_a7f6" data-sup="sup">1</b>。根据实际需求选择合适的查询语句和条件,可以大大提高查询效率和数据处理的准确性。
Top