2016-10-28 7 views
0

私は2つのテーブル:tbl_posttbl_tagsを持っています。 tbl_postカンマ区切りの値を含む列を選択すると、IDが含まれます

、フィールドtags配列としてtbl_tagsからIDがを含有します。 例:( '15' 例)'1,3,15,20'または'4,15,6,21'

私は、その場tagstbl_tagsからIDが含まれていtbl_postからレコードを選択します。

どうすればいいですか?

+0

あなたのスキーマを変更する必要があります試みることができます。カンマで区切られた値を列に入れることは、クエリを扱いにくくするため、悪い考えです。 – Blorgbeard

+0

@a_horse_with_no_name私は、 –

答えて

0

何について:

SELECT * FROM tbl_post WHERE tbl_post.tags LIKE '%15%'; 

ORあなたのコメントを1として

SELECT * FROM tbl_post WHERE Contains(tbl_post.tags, '15'); 

、あなたはあなたができるならば、これは

DECLARE @id INT = 15 
DECLARE @stringId VARCHAR(50) = CAST(@id AS VARCHAR(50)) 

SELECT * 
FROM tbl_post 
WHERE tbl_post.tags = @stringId -- When there is only 1 id in the table 
OR tbl_post.tags LIKE @stringId + ',%' -- When the id is the first one 
OR tbl_post.tags LIKE '%,' + @stringId + ',%' -- When the id is in the middle 
OR tbl_post.tags LIKE '%,' + @stringId -- When the id is at the end 

Referenced from this SO post

+0

の 'tags'が' 1,3,154'ならば何を使っていますか? – Blorgbeard

+0

@Blorgbeard私はこれを処理するための答えを更新しましたが、効率的に設計されたDBスキーマよりもカンマで区切ったリストの値を使用するのは非常に良い理由が必要です。 – ske57

+0

ああ、私は同意します。私はOPではない。ちょうどバグに気づいた。また、3つの別々の節の代わりに '%、15、% ''のような 'where('、 '+ tbl_post.tags +')のようなことをすることもできます。 – Blorgbeard

関連する問題