mysql选择查询多行的位置

时间:2015-10-02 18:36:27

标签: mysql sql

我想选择post_id where(meta_key = group_name和meta_value = Caucaia)和(meta_key = _featured和meta_value = 1)

表:wp_postmeta

post_id | meta_key | meta_value
---------------------------
746     | group_name | Caucaia
746     | _featured  | 1
747     | group_name | Caucaia
747     | _featured  | 0
1791    | group_name | Aruba
1791    | _featured  | 1

我尝试了以下查询,但无效

SELECT `post_id` FROM `wp_postmeta` WHERE (`meta_key` = 'group_name' and `meta_value` ='Caucaia' and `post_id` in (746, 747, 731, 1791, 1799)) or (`meta_key` = '_featured' and `meta_value` ='1' and `post_id` in (746, 747, 731, 1791, 1799)) GROUP BY `post_id`

如何进行查询以从多行中进行选择?或者还有其他方式吗?

2 个答案:

答案 0 :(得分:1)

使用聚合:

SELECT `post_id`
FROM `wp_postmeta`
WHERE (`meta_key` = 'group_name' and `meta_value` ='Caucaia' and `post_id` in (746, 747, 731, 1791, 1799)) or
      (`meta_key` = '_featured' and `meta_value` ='1' and `post_id` in (746, 747, 731, 1791, 1799))
GROUP BY `post_id`
HAVING COUNT(*) = 2;

实际上,我注意到两个列表是相同的。我会用list constructors写这个:

SELECT `post_id`
FROM `wp_postmeta`
WHERE (post_id` in (746, 747, 731, 1791, 1799)) AND
      (meta_key, meta_value) IN (('group_name', 'Caucaia'), ('_featured', '1'))
GROUP BY `post_id`
HAVING COUNT(*) = 2;

答案 1 :(得分:0)

一旦这样做,就是拥有一个包含所需组合的where子句,并计算它返回的行数:

SELECT   post_id
FROM     wp_postmeta
WHERE    (meta_key = 'group_name' AND meta_value = 'Caucaia') OR 
         (meta_key = '_featured' AND meta_value = '1')
GROUP BY post_id
HAVING   COUNT(*) = 2