简体   繁体   中英

SQL inner join two tables

I'm importing data from a SQL database and binding it with Angular.js. I don't know SQL well and having a few problems with this.

What I would like to do is have the the relevant image to appear with the post. This is what I have come up with so far.

select posts.id, posts.name, posts.description, posts.date, posts.email 
from posts Inner Join images on images.id, images.post_id, images.image 
order by posts.date desc

The schema is

posts(table):

id(pk), name, description, date, email

images(table):

id, post_id(fk), image

You got the syntax a bit wrong. In the join you need to specify how the two tables are related. Do this instead:

select 
posts.id, posts.name, posts.description, posts.date, posts.email, image.image
from posts 
Inner Join images on images.post_id = posts.id 
order by posts.date desc

The correct syntax is:

select p.id, p.name, p.description, p.date, p.email, images.id, i.image
from posts p Inner Join
     images i
     on i.post_id = p.id
 order by p.date desc;

You should learn the basic syntax of SQL if you are going to use it effecctively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM