1

假设我有一个 MySQL 表 (meta_table),如下所示,其中包含以下数据:

meta_id,post_id,meta_key,meta_value
5,10,my_key1,value1
10,11,my_key2,value2
15,12,my_key3,value3
35,11,my_key4,value4

如果 meta_value 是 value2 和 value4(答案应该是 11),我如何获得 post_id。我试过这个:

SELECT post_id from meta_table where meta_value='value2' and meta_value='value4' 

但它不会返回 11 作为 post_id。有什么建议么?

4

5 回答 5

2
SELECT post_id
from meta_table 
where meta_value IN ('value2', 'value4')
GROUP BY post_id
HAVING COUNT(*) = 2;

SQL 小提琴演示

于 2012-12-03T09:07:20.680 回答
2

加入:

SELECT a.post_id
FROM meta_table AS a
JOIN meta_table AS b ON a.post_id = b.post_id
WHERE a.meta_value = 'value2' AND b.meta_value = 'value4'

http://www.sqlfiddle.com/#!2/96d2b/4/0

于 2012-12-03T09:08:46.607 回答
1

尝试使用OR

SELECT post_id from meta_table where meta_value='value2' OR meta_value='value4'

或者你可以使用IN

SELECT post_id from meta_table where meta_value IN ('value2', 'value4')
于 2012-12-03T09:07:04.160 回答
0

它应该是 :

SELECT post_id from meta_table where meta_value='value2' or meta_value='value4'

于 2012-12-03T09:06:59.140 回答
0

查询是: -

SELECT post_id from meta_table
where meta_value='value2' or meta_value='value4'
GROUP BY post_id
于 2012-12-03T09:08:47.067 回答