For k vectors v1, v2, ..., vk, if c1v1 + c2v2 + ...+ ckvk = 0 only happens when c1 = c2 = ... = ck = 0, the vectors v1, v2, ..., vk are linearly independent.
Otherwise, they are linearly dependent and one of them is a linear combination of the others.
∫t0t0+Tsin(mω0t)dt=0for all m∫t0t0+Tcos(mω0t)dt=0for all m∫t0t0+Tcos(mω0t)sin(nω0t)dt=0for all m,n∫t0t0+Tsin(mω0t)sin(nω0t)dt=⎩⎨⎧0,2T,m=nm=n∫t0t0+Tcos(mω0t)cos(nω0t)dt=⎩⎨⎧0,2T,m=nm=n
The database maintains the relationships between these tables と ensures data consistency と security.
SQLの基礎
SQL (Structured Query Language) is the stとard language for working with relational databases.
SQLでは次の操作ができます:
Create databases と tables (CREATE)
データの検索(SELECT)
データの挿入(INSERT)
データの更新(UPDATE)
データの削除(DELETE)
例えば:
sql
SELECT * FROM users;
これはusersテーブルの全データを検索します。
SQL is a fundamental tool for working with relational databases such as PostgreSQL, MySQL, と SQLite.
PostgreSQLの基本操作
1. Create a database と table
sql
-- Create a databaseCREATE DATABASE mydb;-- Connect to the database\c mydb-- Create a tableCREATE TABLE users ( id SERIAL PRIMARY KEY, username VARCHAR(60) NOT NULL, email VARCHAR(100) UNIQUE NOT NULL, age INT, created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
注意:列はフィールド名データ型[(長さ)][制約/修飾子]の形式です。
2. データベースやテーブルの削除、またはテーブルのデータ消去
sql
-- Drop a database (you cannot drop the database you are currently connected to)DROP DATABASE mydb;-- Drop a table (including its structure と data)DROP TABLE exTable;-- Clear table data while keeping its structure (faster than DELETE, but does not log individual rows)TRUNCATE TABLE exTable;--
3. 列の追加とデータ型の変更
sql
-- Add a column:ALTER TABLE exTable ADD COLUMN age INT;-- Change a data type:ALTER TABLE exTable ALTER COLUMN email TYPE VARCHAR(255);
4. Read, insert, update, と delete data
検索
sql
-- Query all dataSELECT * FROM exTable;-- Filtered querySELECT username, email FROM exTable WHERE id > 1;-- Pattern matching (ILIKE is case-insensitive, a PostgreSQL feature)SELECT username, email FROM exTable WHERE username ILIKE 'tech%';-- Sort と limit; ascending by default, DESC for descendingSELECT * FROM exTable ORDER BY created_time DESCLIMIT 6;
追加
sql
-- Insert one rowINSERT INTO exTable (username, email) VALUES ('alice', 'alice@example.com');-- Insert multiple rowsINSERT INTO exTable (username, email)VALUES('bob', 'bob@example.com'),('charlie', 'charlie@example.com');
更新
sql
UPDATE exTable SET email = 'alice_new@example.com'WHERE username = 'alice';
Prerequisite: You should know how to create tables と perform basic CRUD operations.
Goal: Write more precise queries, understと data constraints, と get an introduction to joins across multiple tables.
複数条件の組み合わせ:AND / OR / NOT
sql
-- AND: both conditions must be trueSELECT * FROM usersWHERE age >= 18 AND age <= 30;-- OR: either condition can be trueSELECT * FROM usersWHERE username = 'alice' OR username = 'bob';-- NOT: excludeSELECT * FROM usersWHERE NOT age < 18;
Ranges と lists: BETWEEN / IN
sql
-- BETWEEN (inclusive)SELECT * FROM usersWHERE age BETWEEN 18 AND 30;-- IN (equivalent to multiple OR conditions, but more concise)SELECT * FROM usersWHERE username IN ('alice', 'bob', 'charlie');-- NOT IN (exclude a list)SELECT * FROM usersWHERE username NOT IN ('alice', 'bob');
NULLの判定:IS NULL / IS NOT NULL
sql
-- 年齢が未入力のユーザーを検索(= NULL は使用しない)SELECT * FROM usersWHERE age IS NULL;-- Find users who have entered their ageSELECT * FROM usersWHERE age IS NOT NULL;
NULL is not the same as an empty string '' or 0; it represents an "unknown value" と must be checked with IS NULL.
集計関数:データを集計する
関数
役割
COUNT()
件数
SUM()
合計
AVG()
平均
MAX()
最大値
MIN()
最小値
sql
-- Number of usersSELECT COUNT(*) FROM users;-- Average user ageSELECT AVG(age) FROM users;-- Maximum と minimum user agesSELECT MAX(age), MIN(age) FROM users;-- 注意:COUNT(*) は全行を数え、COUNT(age) はNULLを除外します。SELECT COUNT(*), COUNT(age) FROM users;
GROUP BY:グループごとの集計
Group the data by a column, then aggregate each group.
sql
-- Create an orders table for this exampleCREATE TABLE orders ( id SERIAL PRIMARY KEY, username VARCHAR(60) NOT NULL, product VARCHAR(60), amount INT, created_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP);INSERT INTO orders (username, product, amount) VALUES('alice', 'book', 120),('alice', 'pen', 30),('bob', 'book', 120),('bob', 'bag', 200),('charlie','pen', 30);
sql
-- Number of orders per userSELECT username, COUNT(*) AS order_countFROM ordersGROUP BY username;-- Total spending per userSELECT username, SUM(amount) AS total_spentFROM ordersGROUP BY username;
出力例:
username
total_spent
alice
150
bob
320
charlie
30
クエリの実行順序(重要)
Many SQL errors beginners encounter come from misunderstとing the execution order:
FROM → Choose the data source
WHERE → Filter source rows
GROUP BY → Group rows
HAVING → Filter grouped results
SELECT → Select columns (aliases become available here)
ORDER BY → Sort rows
LIMIT → Limit the number of rows
sql
-- Common mistake: using an alias from SELECT in WHERE-- ❌ Incorrect: WHERE runs before SELECT, so total_spent does not exist yetSELECT username, SUM(amount) AS total_spentFROM ordersWHERE total_spent > 100 -- This causes an error!GROUP BY username;-- ✅ Correct: use HAVINGSELECT username, SUM(amount) AS total_spentFROM ordersGROUP BY usernameHAVING SUM(amount) > 100;
Give columns と tables aliases with AS
sql
-- Column aliases (make output easier to read)SELECT username AS username, SUM(amount) AS total_spendingFROM ordersJOIN users ON orders.user_id = users.idGROUP BY username;-- Table aliases (shorten long names; useful in multi-table queries)SELECT u.username, o.product, o.amountFROM users AS uJOIN orders AS o ON u.id = o.user_id;
練習問題
次の2つのテーブルを使って練習しましょう:
sql
-- Prepare sample dataINSERT INTO users (username, email) VALUES('alice', 'alice@example.com'),('bob', 'bob@example.com'),('charlie', 'charlie@example.com');INSERT INTO orders (user_id, product, amount) VALUES(1, 'book', 120),(1, 'pen', 30),(2, 'book', 120),(2, 'bag', 200);-- charlie has no orders
Query every username と their total order amount, sorted by total amount in descending order
合計支出が100を超えるユーザーを探す
注文のないユーザーも含めて全ユーザーを検索する(ヒント:LEFT JOIN)
商品ごとの販売回数を集計する
本章の構成
T+1 SQL fundamentals
├── Conditional queries
│ ├── AND / OR / NOT
│ ├── BETWEEN / IN
│ └── IS NULL / IS NOT NULL
├── Aggregation
│ ├── COUNT / SUM / AVG / MAX / MIN
│ ├── GROUP BY
│ └── HAVING
├── クエリの実行順序
│ └── FROM→WHERE→GROUP BY→HAVING→SELECT→ORDER BY→LIMIT
└── Joins across tables
├── 外部キー REFERENCES
├── INNER JOIN
├── LEFT JOIN
└── Column/table aliases with AS
PythonでPostgreSQLを使う
1. 依存パッケージのインストール
Pythonからデータベースを操作するには、まずpsycopg2パッケージをインストールします。
powershell
pip install psycopg2-binary
2. PythonからSQLを実行する
python
import psycopg2# Connect to the databaseconn = psycopg2.connect( dbname="mydb", user="your_user", password="your_password", host="localhost", port="5432")
A foreign key constrains the relationship between two tables と prevents "orphaned data".
sql
-- Rebuild the score table (drop it first if it already exists)DROP TABLE IF EXISTS score;-- The sid と cid columns in score reference the student と course tables respectivelyCREATE TABLE score ( sid INT REFERENCES student(sid), cid INT REFERENCES course(cid), score INT);
Here, both sid と cid are foreign keys.
sidはstudentテーブルのsidを参照します。
cidはcourseテーブルのcidを参照します。
Foreign keys link tables と ensure data consistency.
例えば、studentテーブルにsid=100の学生がいない場合、次の文は実行できません:
sql
INSERT INTO score VALUES (100, 1, 90);
外部キーによりscore.sidにはstudentテーブルに存在するsidを指定する必要があるため、データベースはエラーを返します。
同様に、courseテーブルに存在しない科目IDを使って成績を挿入することはできません。
Foreign keys therefore prevent references to nonexistent data と keep data consistent across tables.
Beginner-friendly and simple to use, with almost no learning curve
Offers a good range of tokenization features and export formats, Excelや大納言などの形式で出力できます
Disadvantages:
Limited features and customization
Difficult to automate with large texts; Python + the MeCab module + a dictionary package is recommended
2. Install the MeCab application (Windows)
ダウンロードしてインストール:mecab-0.996.exe
The application itself is small, so installing it on drive C is recommended. To install it on drive D, add it to the system environment variables after installation.
MeCab requires a dictionary file. Installation automatically creates the ipadic dictionary, which is outdated and no longer updated.
Replacing it with a custom dictionary package is strongly recommended!!!
Custom dictionary package: This example uses the latest unidic-cwj-202512 released by the National Institute for Japanese Language and Linguistics.
After downloading unidic-cwj-202512.zip, extract it to a folder of the same name in the root of drive D (or C).
Copy the path of the unidic-cwj-202512 folder: "D:\unidic-cwj-202512".
Find the installed MeCab folder and open "D:\MeCab\etc\mecabrc" in Notepad (use the corresponding path if installed on drive C).
Paste the path from step 2 after dicdir =, like this: dicdir = D:\unidic-cwj-202512.
This sets the custom dictionary MeCab will use at runtime.
Next, use MeCab on Windows
Search for PowerShell in the lower-left search box. Right-click it and choose Run as administrator.
Because of encoding limitations, set the PowerShell console encoding before using MeCab.
Enter the following in the command line: $OutputEncoding = [Console]::InputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
This forces UTF-8 encoding to prevent garbled text.
Enter the mecab command to start the mecab program, which will wait for text or a file to tokenize.
The following describes manual input and file-based input/output.
Manual input is simple: copy the text to tokenize and paste it into the command line.
Press Enter; the tokenized result appears on screen and can be copied.
To tokenize an entire file (it must be a .txt file; convert other formats to .txt first)
Enter the following command (use -o to specify the output file and -O to specify the output format; the options are case-sensitive): mecab "C:\Users\...\test.txt" -o "C:\Users\...\ed.txt" -Ounidic Notes: "C:\Users\...\test.txt" This is the path to the file you want to tokenize, "C:\Users\...\ed.txt" this is the path where you want to save the tokenized output, -Ounidic means: use the -O option to select the unidic output format (the default format can be customized; see Custom tokenization below).
3. Install Python to use with MeCab (recommended)
Download and install Python and an editor (PyCharm, VS Code, Zed, or another editor)
Add Python to the environment variables
Search for environment variables in the lower-left Windows search box, open Edit the system environment variables, then click Environment Variables in the lower-right.
Under User variables for xx, select Path, click Edit, then click New.
Copy and paste the path to the Python installation folder, then click OK until you close the Environment Variables settings.
Example: D:\Python3.12.9\
Use the pip package manager to install the MeCab package
Enter this in the PowerShell command line: pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
This command sets the Tsinghua package mirror. Without it, installing packages with pip from China can be difficult.
In the PowerShell command line, run pip install mecab-python3 to install the MeCab package.
Open your editor and configure the Python environment (the steps differ by editor; search for a tutorial if needed).
Everything is ready. Let’s begin!
Enter the following code to import the MeCab package into Python.
python
import MeCab# Specify a dictionary before tokenizing with MeCab, then initialize the MeCab tagger.# Use the custom dictionary unidic-cwj-202512; unidic_path is its location.unidic_path = r"D:\unidic-cwj-202512"
Enter the following code to initialize MeCab.
python
# Initialize the tagger with tagger = MeCab.Tagger(); pass custom options in the parentheses.# -r "{mecabrc}" specifies an empty config file; -d "{unidic_path}" points to the custom dictionary.tagger = MeCab.Tagger(f'-r nul -d "{unidic_path}"') # Output detailed tokenization information by default
Tokenize text or a file and print the result.
python
text = "勉強は大好きだ。"result = tagger.parse(text)print(result)# No output mode was specified, so detailed tokenization information is shown by default.>>>- 名詞,普通名詞,サ変可能,*,*,*日本橋 名詞,固有名詞,地名,一般,*,*,ニホンバシ,ニホンバシ,日本橋,ニホンバシ,日本橋,ニホンバシ,固,*,*,*,*,*,*,地名,ニホンバシ,ニホンバシ,ニホンバシ,ニホンバシ,0,*,*,7830455558742528,28487は 助詞,係助詞,*,*,*,*,ハ,は,は,ワ,は,ワ,和,*,*,*,*,*,*,係助,ハ,ハ,ハ,ハ,*,"動詞%F2@0,名詞%F1,形容詞%F2@-1",*,8059703733133824,29321いい 形容詞,非自立可能,*,*,形容詞,連体形-一般,ヨイ,良い,いい,イー,いい,イー,和,*,*,*,*,*,*,相,イイ,イイ,イイ,イイ,1,C3,*,10716948459561665,38988ところ 名詞,普通名詞,副詞可能,*,*,*,トコロ,所,ところ,トコロ,ところ,トコロ,和,ト濁,基本形,*,*,*,"B1WS2WB3WB4WBjS,B1WS2WB8SjS",体,トコロ,トコロ,トコロ,トコロ,"3,0",C2,*,7249372253397504,26373です 助動詞,*,*,*,助動詞-デス,終止形-一般,デス,です,です,デス,です,デス,和,*,*,*,*,*,*,助動,デス,デス,デス,デス,*,"形容詞%F2@-1,動詞%F2@0,名詞%F2@1",*,7051468750332587,25653ね 助詞,終助詞,*,*,*,*,ネ,ね,ね,ネ,ね,ネ,和,*,*,*,*,*,*,終助,ネ,ネ,ネ,ネ,*,"動詞%F1,名詞%F1,形容詞%F1",*,7903847959896576,28754。 補助記号,句点,*,*,*,*,*,。,。,*,。,*,記号,*,*,*,*,*,*,補助,*,*,*,*,*,*,*,6880571302400,25EOS
Custom tokenization modes
The steps for specifying a MeCab output mode are the same in PowerShell and Python, so the example below uses Python.
python
# Note: Add an entry for each custom output mode to the dictionary dicrc file. Modes already in dicrc can be used directly.# For example, the built-in concise mode wakati tokenizes 「勉強は大好きだ。」 as shown: 勉強 は 大好き だ 。# To use it, append -Owakati to the MeCab initialization command.# That is, add a hyphen, uppercase O, and the output mode, as shown below.tagger = MeCab.Tagger(f'-r nul -d "{unidic_path}" -Owakati')text = "勉強は大好きだ。" # This is the text to tokenize.result = tagger.parse(text)print(result)>>> 勉強 は 大好き だ 。
If you defined a custom tokenization mode in the dictionary’s dicrc file, use the following code to select it along with the dictionary: