1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const mysql = require('mysql2/promise');
async function runQueries() {
const connection = await mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'waimai'
});
try {
// 1. Single table query
console.log("1. List all customers:");
let [rows] = await connection.execute('SELECT * FROM 客户');
console.log(rows);
// 2. Multi-table query using JOIN
console.log("\n2. List all orders with customer and product details:");
[rows] = await connection.execute(`
SELECT 订单.id, 客户.name AS customer_name, 商品.name AS product_name, 订单.number, 订单.total_cost
FROM 订单
JOIN 客户 ON 订单.customer_id = 客户.id
JOIN 商品 ON 订单.商品_id = 商品.id
`);
console.log(rows);
// 3. Sorting
console.log("\n3. List all products sorted by price in descending order:");
[rows] = await connection.execute('SELECT * FROM 商品 ORDER BY price DESC');
console.log(rows);
// 4. Grouping
console.log("\n4. Total sales for each business:");
[rows] = await connection.execute(`
SELECT 商家.name, SUM(订单.total_cost) AS total_sales
FROM 商家
JOIN 商品 ON 商家.id = 商品.business_id
JOIN 订单 ON 商品.id = 订单.商品_id
GROUP BY 商家.id
`);
console.log(rows);
// 5. Filtering after grouping
console.log("\n5. Businesses with total sales over 50:");
[rows] = await connection.execute(`
SELECT 商家.name, SUM(订单.total_cost) AS total_sales
FROM 商家
JOIN 商品 ON 商家.id = 商品.business_id
JOIN 订单 ON 商品.id = 订单.商品_id
GROUP BY 商家.id
HAVING total_sales > 50
`);
console.log(rows);
// 6. Use of aggregate functions
console.log("\n6. Average order value and total number of orders:");
[rows] = await connection.execute(`
SELECT AVG(total_cost) AS avg_order_value, COUNT(*) AS total_orders
FROM 订单
`);
console.log(rows);
// 7. Self-join (assuming we want to find businesses in the same area)
console.log("\n7. Businesses in the same area:");
[rows] = await connection.execute(`
SELECT a.name AS business1, b.name AS business2, a.address
FROM 商家 a
JOIN 商家 b ON LEFT(a.address, 3) = LEFT(b.address, 3) AND a.id < b.id
`);
console.log(rows);
} catch (error) {
console.error('Error executing queries:', error);
} finally {
await connection.end();
}
}
runQueries();No Output
Run the code to generate an output.