Reputation: 393
I'm building an api with Express.js. Right now my very first testes are working. Now, i would like to get values from two different tables. Per example, let's say i have the next 2 tables
Table_A
Id: 1,
Name: Chuck,
Age: 30
Table_B
Id: 1,
NickName: Chuckthulhu,
DateStart: 2018-11-01,
IdTableA: 1
And what i expect to return on my api is:
{Id: 1, Name: "Chuck", NickName: "Chucthulhu", DateStart: "2018-11-01"}
How can i do that? This my code so far:
var express = require("express");
var bodyParser = require("body-parser");
var sql = require("mssql");
var app = express();
app.use(bodyParser.json());
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
next();
});
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
var dbConfig = {
user: "theUser",
password: "thePassword",
server: "theServer",
database: "theDb"
};
var executeQuery = function(res, query){
sql.connect(dbConfig, function (err) {
if (err) {
console.log(err);
res.send(err);
}
else {
// create Request object
var request = new sql.Request();
// query to the database
request.query(query, function (err, result) {
if (err) {
console.log(err);
res.send(err);
}
else {
res.send(result);
}
});
}
});
}
//GET API
app.get("/api/MyApi", function(req, res){
var query = "select * from [Table_A]";
executeQuery (res, query);
});
I'm very new on this. As i see, it's a simple query to get the info... if that's the logic, i just need to do a join
or left join
to the Table_B?
I'm using Javascript, Node and Express.js, and the DB it's on SQL Server Thanx in advance.
Upvotes: 0
Views: 4291
Reputation: 10765
--From your example, IdTableA is the foreign key in Table B which relates it to a record
--in Table A, you would want to Inner Join on that to link it to Table A
--Alias your table''s with a and b and then select the appropriate columns from each
select a.[Id], a.[Name], b.[NickName], b.[DateStart]
from [Table_A] AS a
INNER JOIN [Table_B] AS b
ON b.[IdTableA] = a.[Id]
Upvotes: 1