【问题标题】:Selecting from Different Tables, Sub queries or Joins从不同的表、子查询或连接中选择
【发布时间】:2015-06-06 15:18:35
【问题描述】:

我有两张桌子;我需要做的是选择给定用户的 cmets。我需要 cid 和标题作为结果

posts
pid | heading | body   | username
1     smth....  smth..   u1
2     smth....  smth..   u2

帖子

cid | body   | username
1     smth..   u1
2     smth..   u2

我尝试使用 JOINS,主要是 INNER。但答案是错误的。然后我再次尝试使用子查询答案是错误的,但这次它的答案与以前不同。现在我正在尝试将 INNER JOINS 与子查询一起使用。不知道有没有可能。

我尝试过的一些 SQL;因为尝试的东西太多,所以我不会全部发布。

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')

【问题讨论】:

  • 你和桌子有什么关系吗?
  • 不是在表之间,而是两个表username字段是users表上的外键

标签: php mysql join subquery


【解决方案1】:

根据您发布的查询,表格之间似乎存在关系

`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'

【讨论】:

  • 必须在 where 子句中添加 c.username 部分,但这有效SELECT c.comment_id, p.post_id, c.friendly_url, c.heading` FROM post p JOIN comments c在 p.post_id = c.post_id 其中username = c.'u1'`谢谢!! :)
猜你喜欢
  • 2023-03-20
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
  • 2015-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-24
相关资源
最近更新 更多