简体   繁体   English

SQL:SQL连接帮助

[英]SQL: help with sql joins

Hi I have an app that has posts, tags, and a tag_ref link table. 嗨,我有一个具有帖子,标签和tag_ref链接表的应用。 I want to query for posts that have a specific tag association. 我想查询具有特定标签关联的帖子。

The database structure is as follows: 数据库结构如下:

posts 帖子

id ID

tags_ref tags_ref

row_id row_id

table

tag_id tag_id

tags 标签

id ID

safe_tag safe_tag

tag 标签

My query basically goes if $safe_tag is not null then join tags_ref on post.id = tags_ref.row_id, join tags on tags_ref.tag_id = tags.id, where tags_ref.table = 'posts' and tags.safe_tag = 'food' and post.city_id = 2 我的查询基本上是如果$ safe_tag不为null,然后在post.id = tags_ref.row_id上加入tags_ref,在tags_ref.tag_id = tags.id上加入标签,其中tags_ref.table ='posts'和tags.safe_tag ='food'并且post.city_id = 2

Is this query correct? 这个查询正确吗? Am I using the correct type of join? 我使用的连接类型正确吗?

SELECT *
FROM (`posts`)
INNER JOIN `tags_ref` ON `posts`.`id` = `tags_ref`.`row_id`
INNER JOIN `tags` ON `tags_ref`.`tag_id` = `tags`.`id`
WHERE `tags_ref`.`table` = 'posts'
AND `tags`.`safe_tag` = 'food'
AND `posts`.`city_id` = '2' 

I'm getting odd results that have no tags associated at all. 我得到的奇怪结果根本没有关联的标签。

Thanks 谢谢

This will only return results from the posts table, as opposed to all columns in the join tables. 这将只返回posts表中的结果,而不是join表中的所有列。 I have removed the city_id constraint that you haven't specified in your question text (and that was in your query): 我已经删除了您尚未在问题文本中指定的city_id约束(并且在查询中指定):

SELECT P.*
FROM posts AS P
  INNER JOIN tags_ref AS TR ON P.id = TR.row_id
  INNER JOIN tags AS T ON TR.tag_id = T.id
WHERE TR.table = 'posts'
AND T.safe_tag = 'food'

I have also added table aliases and removed the quoting. 我还添加了表别名并删除了引用。

If you do not get any results, that would suggest to me that there are no posts with the food . 如果您没有得到任何结果,那将向我暗示没有food张贴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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