sql查詢記錄
1. 如何獲取sql查詢當前數據上一條和下一條的記錄
方法一:x0dx0a查詢上一條記錄的SQL語句(如果有其他的查詢條件記得加上other_conditions以免出現不必要的錯誤):x0dx0a1x0dx0aselect * from table_a where id = (select id from table_a where id < {$id} [and other_conditions] order by id desc limit 1) [and other_conditions];x0dx0a查詢下一條記錄的SQL語句(如果有其他的查詢條件記得加上other_conditions以免出現不必要的錯誤):x0dx0a1x0dx0aselect * from table_a where id = (select id from table_a where id > {$id} [and other_conditions] order by id asc limit 1) [and other_conditions];
2. SQL簡單查詢記錄
SQL基礎查詢入門指南
1. 基礎查詢操作
- 1) 選擇部分數據:使用SELECT語句,指定需要的欄位,如:SELECT * FROM student;
- 2) 獲取所有數據:SELECT * FROM student; 會顯示表中的所有記錄。
- 3) 設定新列名:如 SELECT name AS 'Full_Name' FROM student;
- 4) 去重處理:使用DISTINCT關鍵字,如 SELECT DISTINCT name FROM student;
注意事項:SQL語句以英文分號結束,關鍵字大小寫不敏感,列名需規范,避免空格和單引號。
2. 指定查詢條件
- WHERE子句用於設置條件,如 SELECT * FROM student WHERE age > 18;
- 查詢順序:先FROM,後WHERE,最後SELECT。
3. 注釋與語句規范
- 單行注釋:-- 注釋內容
- 多行注釋:/* 注釋內容 */
- 建議保持語句清晰,避免空行和亂碼。
4. 運算符運用
- 算術:+、-、*、/
- 比較:=, !=, >, >=, <, <=
- null值判斷:is null 或 is not null
- 邏輯:not, and, between, or (可以用 in 替代)
練習實例:自定義SQL語句完成上述運算符和條件的練習。
5. 字元串模糊查詢
- like操作符:查詢姓氏或姓名特定模式,如 SELECT * FROM student WHERE name LIKE '猴%'
- 匹配最後一個字:SELECT * FROM student WHERE name LIKE '%猴'
- 包含特定字:SELECT * FROM student WHERE name LIKE '%猴'
- 復合條件:SELECT * FROM student WHERE last_name = '王' AND LENGTH(name) = 3;
3. sql查詢按兩個欄位查詢重復記錄
用關鍵字 stinct,select stinct 欄位,是不重復的意思。代碼的實例如下:
查詢order_id和loan_lind兩個欄位相同的記錄:
select distinct a.order_preview_id, a.order_id, a.loan_kind
from ddk_order_preview_info a
join ddk_order_preview_info b
on a.order_preview_id != b.order_preview_id
where a.order_id = b.order_id and a.loan_kind = b.loan_kind;
(3)sql查詢記錄擴展閱讀
SQL資料庫查詢出一張表中重復的數據,按某個欄位來查找的實例:
例如表名為Course:
補充:
如:查詢每個姓名出現大於2次,SQL如下
SELECT COUNT(NAME) as '出現次數', NAME FROM 表名
GROUP BY NAME HAVING count(NAME) > 2 ORDER BY 出現次數 DESC