从不同的表、子查询或连接中选择
Selecting from Different Tables, Sub queries or Joins
我有两张桌子;我需要做的是 select 给定用户的评论。我需要 cid 和标题作为结果
posts
pid | heading | body | username
1 smth.... smth.. u1
2 smth.... smth.. u2
posts
cid | body | username
1 smth.. u1
2 smth.. u2
我尝试过使用 JOINS,主要是 INNER。但答案是错误的。然后我再次尝试使用子查询答案是错误的,但这次它的答案与以前不同。现在我正在尝试将 INNER JOINS 与子查询一起使用。不知道可不可以。
一些SQL我已经尝试过;我不会 post 因为我尝试了太多东西。
SELECT `comment_id`, `post`.`post_id`, `friendly_url`, `heading` FROM `post`,`comments` WHERE `post`.`post_id` IN (SELECT `comments`.`post_id` FROM `comments` WHERE `username` = ?)
SELECT `post`.`post_id`, `friendly_url`, `heading` FROM `post`INNER JOIN `comments` ON `post`.`post_id`= `comments`.`post_id` WHERE `post`.`post_id` IN (SELECT `comments`.`post_id` FROM `comments` WHERE `username` = 'chichi')
根据您发布的查询,似乎存在关系 b/w 表
`post`.`post_id` = `comments`.`post_id`
所以你可以尝试使用 INNER JOIN
比如
SELECT c.`comment_id`, p.`post_id`, c.`friendly_url`, c.`heading`
FROM `post` p JOIN `comments` c ON p.`post_id` = c.`post_id`
WHERE `username` = 'u1'
我有两张桌子;我需要做的是 select 给定用户的评论。我需要 cid 和标题作为结果
posts
pid | heading | body | username
1 smth.... smth.. u1
2 smth.... smth.. u2
posts
cid | body | username
1 smth.. u1
2 smth.. u2
我尝试过使用 JOINS,主要是 INNER。但答案是错误的。然后我再次尝试使用子查询答案是错误的,但这次它的答案与以前不同。现在我正在尝试将 INNER JOINS 与子查询一起使用。不知道可不可以。
一些SQL我已经尝试过;我不会 post 因为我尝试了太多东西。
SELECT `comment_id`, `post`.`post_id`, `friendly_url`, `heading` FROM `post`,`comments` WHERE `post`.`post_id` IN (SELECT `comments`.`post_id` FROM `comments` WHERE `username` = ?)
SELECT `post`.`post_id`, `friendly_url`, `heading` FROM `post`INNER JOIN `comments` ON `post`.`post_id`= `comments`.`post_id` WHERE `post`.`post_id` IN (SELECT `comments`.`post_id` FROM `comments` WHERE `username` = 'chichi')
根据您发布的查询,似乎存在关系 b/w 表
`post`.`post_id` = `comments`.`post_id`
所以你可以尝试使用 INNER JOIN
比如
SELECT c.`comment_id`, p.`post_id`, c.`friendly_url`, c.`heading`
FROM `post` p JOIN `comments` c ON p.`post_id` = c.`post_id`
WHERE `username` = 'u1'