English 中文(简体)
你们如何在神话或铁路中这样做
原标题:How do you do this in mysql or rails

你有一个职位表和一个职位表,两个职位都由一个职位——职位表挂钩。

......

员额

tags has id/name

职位——主 id/post_id/tag_id

in rails terminology, I have a Post Model that has many Tags through AssetTags.

I m trying to query for a post that has 2 specific tags. ......if there is a rails tag and a mysql tag, I want a query that returns a post that only has those two tags.

说 明

这样做的任何方法(使用搜索逻辑的Im)或神秘性?

最佳回答

这一结构将包含两个方面的员额归来。

select 
  p.* 
from 
  posts p
  ,asset_tags atg1
  ,asset_tags atg2
  ,tags t1
  ,tags t2
where
  p.id = atg1.post_id
and t1.id = atg1.tag_id
and t1.tag =  MySQL  
and p.id = atg2.post_id
and t2.id = atg2.tag_id
and t2.tag =  Rails 
;

至于通过积极记录进行这项工作,一种替代办法是询问每一方,然后到处;由此形成的阵列,以找到双方的交汇点。

问题回答

鉴于这些模式:

def Post
  has_many :asset_tags
  has_many :tags, :through => :asset_tags
end

def AssetTag
  has_one :post
  has_one :tag
end

def Tag
  has_many :asset_tags
  has_many :posts, :through => :asset_tags
end

你可以这样做:

Post.joins(:asset_tags => :tag).where(
  "tags.name in ( ? ,  ? )",  foo ,  bar  )

现在,这实际上与<条码>s_many :通过协会——我不敢肯定,如果有哪怕是一只微薄的皮,那么就没有。

For mysql, sure, you can get the data

 SELECT p.*
   FROM posts p 
   JOIN post_tags pt
     ON p.post_id = pt.post_id
  WHERE pt.tag_id in (tagId1, tagId2)

我没有使用铁路主动通融,但我相信,这将符合铁路线。

 get( posts );
 join( post_tags , post_id );
 where_in( tag_id , array(tagId1, tagId2);
 execute();

John Bachir的答复可修改为......

Post.joins(:asset_tags => :tag)
    .where("tags.name in ( ? )",  foo )
    .where("tags.name in ( ? )",  bar )




相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签