【问题标题】:PHP combine two tables and list all from first tablePHP合并两个表并从第一个表中列出所有
【发布时间】:2018-11-23 07:06:53
【问题描述】:

我想合并两张表。 表 A:具有多个具有唯一 URL 的帖子,表 B 对表 A 中的特定帖子进行投票。 现在我想列出表 A 中的所有行,如果帖子在表 B 中有投票,则将其附加到一行。 我试过这个,但它排除了将表 A 与表 B 匹配的帖子。它只返回没有任何投票。

SELECT a.id,a.url,a.content,a.sourcetype,a.width,a.height,a.totalvotes,a.score, b.postid,b.userid,b.votetype
  FROM create_general a
  LEFT JOIN votes b ON a.url=b.postid
  WHERE a.status='1' and a.score > 0 order by a.url desc
  LIMIT 24

【问题讨论】:

  • 看起来您需要使用 post id LEFT JOIN votes b ON a.id=b.postid 加入两个表

标签: php mysql sql


【解决方案1】:

也许了解更多有关表结构的信息会很好,但你肯定会在你的 on 子句中做一些连接:

ON a.url=b.postid

这表示,“table a”中的“url”必须与“table b”中的“postid”相同。

通常一个 url 看起来像这样:“https://google.de”,而 postid 只是一个数字,可能是“7”,所以它们不能相同。

【讨论】:

  • url = aw43sa2324 和 postid 是一样的。这只是我使用的结构。
  • 使用字符串数据类型(如 url 或上面评论中显示的数据类型)连接表是个坏主意。使用 int 数据类型。顺便问一下,a.totalvotes 是一个真实的字段吗?
猜你喜欢
  • 1970-01-01
  • 2021-10-12
  • 2014-01-27
  • 2019-04-03
  • 1970-01-01
  • 2016-11-29
  • 1970-01-01
相关资源
最近更新 更多