我正在运行一个express服务器并连接到mysql数据库。我有两个表,通过 user_id
. 当用户提供我需要查询的电子邮件地址时 users
找到 user_id
然后运行另一个查询以加入 tracking
table。实现这一目标的最佳方法是什么?另外,对于代码的任何部分的任何最佳实践建议都将不胜感激!
谢谢
mysql数据库
CREATE TABLE users (
user_id INT NOT NULL AUTO_INCREMENT UNIQUE,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) DEFAULT NULL,
email VARCHAR(320) NOT NULL UNIQUE,
date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (user_id)
);
CREATE TABLE tracking (
tracking_id INT NOT NULL AUTO_INCREMENT,
user_id INT NOT NULL,
metric VARCHAR(100) NOT NULL,
unit VARCHAR(100) NOT NULL,
amount DOUBLE DEFAULT NULL,
date_tracked DATE,
date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (tracking_id),
INDEX user_ind (user_id),
FOREIGN KEY (user_id)
REFERENCES users(user_id)
ON DELETE CASCADE
);
快车(nodejs)
const express = require("express");
const app = express();
const port = 3000;
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "",
user: "",
password: "",
database: "tracker"
});
app.get("/data/:email/metric/:metric", (req, res) => {
console.log(req.params);
let user_id = "";
connection.connect();
connection.query(
`SELECT user_id FROM users WHERE email = '${req.params.email}';`,
function(error, results, fields) {
if (error) throw error;
user_id = results[0].user_id;
}
);
connection.query(
`SELECT users.first_name, users.last_name, users.email, tracking.metric, tracking.unit, tracking.amount, tracking.date_tracked FROM users JOIN tracking ON users.user_id = tracking.user_id WHERE users.user_id = '${user_id}' AND metric = '${
req.params.metric
}';`,
function(error, results, fields) {
if (error) throw error;
res.send(results);
}
);
connection.end();
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
2条答案
按热度按时间gr8qqesn1#
我需要查询用户以找到用户id,然后运行另一个查询以加入跟踪表。实现这一目标的最佳方法是什么?
只需一个查询即可实现:
另外,对于代码的任何部分的任何最佳实践建议都将不胜感激!
首先,您应该在服务器启动后连接到mysql。
每次请求时连接和断开连接都会影响性能(打开套接字并在外部连接是一项昂贵的任务)
所以试试这样:
您应该知道的另一个好做法是与promise.all([])并行运行查询。当您需要运行多个不相关的查询时,您可以一个接一个地执行它们,从而使所有结果的总等待时间大大缩短。
jvidinwx2#
只需一个查询就可以完成这一点
JOIN
table放在table上user_id
```SELECT
u.first_name,
u.last_name,
u.email,
t.metric,
t.unit,
t.amount,
t.date_tracked
FROM users u
INNER JOIN tracking AS t ON t.user_id = u.user_id
WHERE u.email = '' AND t.metric = ''
const values = [
req.params.email,
req.params.metric
];
connection.query(
'SELECT ... WHERE u.email = ? AND t.metric = ?',
values,
(err, results, fields) => {
if (err) return next(e); // propagate the error to Express, rather than throwing in the callback
}
);