背景
我通过php生成sql查询,以便在wordpress数据库上使用。
问题:
有时我需要两组或更多组(行)相同的信息。
问题:
使用我的示例查询和我当前的sql设置,我只能返回一组信息,即使我想要获得2套。如何使用sql完成我想要的结果?
示例查询: 使用php生成
SELECT suborgs.meta_value
FROM (
SELECT suborgs2.*
FROM wp_postmeta suborgs2
WHERE suborgs2.meta_key = 'product_relationship'
) suborgs
WHERE suborgs.post_id = '152'
OR suborgs.post_id = '152';
结果:
+-----------------------------------+
| meta_value |
+-----------------------------------+
| a:2:{i:0;s:2:"42";i:1;s:3:"199";} |
+-----------------------------------+
期望的结果:
+-----------------------------------+
| meta_value |
+-----------------------------------+
| a:2:{i:0;s:2:"42";i:1;s:3:"199";} |
| a:2:{i:0;s:2:"42";i:1;s:3:"199";} |
+-----------------------------------+
注意:这是我的示例查询所需的结果。该查询可能有9个以上对同一suborgs.post_id
的引用,在这种情况下,我的结果中会有9行。为了迭代这个,我创建了第二个示例,结果如下。
示例查询2:
SELECT suborgs.meta_value
FROM (
SELECT suborgs2.*
FROM wp_postmeta suborgs2
WHERE suborgs2.meta_key = 'product_relationship'
) suborgs
WHERE suborgs.post_id = '152'
OR suborgs.post_id = '162'
OR suborgs.post_id = '156'
OR suborgs.post_id = '152'
OR suborgs.post_id = '154'
OR suborgs.post_id = '152'
OR suborgs.post_id = '162';
结果:
+-----------------------------------+
| meta_value |
+-----------------------------------+
| a:2:{i:0;s:2:"42";i:1;s:3:"199";} |
| a:2:{i:0;s:2:"31";i:1;s:3:"923";} |
| a:2:{i:0;s:2:"63";i:1;s:3:"423";} |
| a:2:{i:0;s:2:"61";i:1;s:3:"132";} |
+-----------------------------------+
期望的结果:
+-----------------------------------+
| meta_value |
+-----------------------------------+
| a:2:{i:0;s:2:"42";i:1;s:3:"199";} |
| a:2:{i:0;s:2:"31";i:1;s:3:"923";} |
| a:2:{i:0;s:2:"63";i:1;s:3:"423";} |
| a:2:{i:0;s:2:"42";i:1;s:3:"199";} |
| a:2:{i:0;s:2:"61";i:1;s:3:"132";} |
| a:2:{i:0;s:2:"42";i:1;s:3:"199";} |
| a:2:{i:0;s:2:"31";i:1;s:3:"923";} |
+-----------------------------------+
答案 0 :(得分:1)
使用子查询而不是IN
:
SELECT suborgs.*
FROM wp_postmeta suborgs JOIN
(SELECT '152' as post_id UNION ALL SELECT '162' UNION ALL SELECT '156' UNION ALL
SELECT '154' UNION ALL SELECT '152' UNION ALL SELECT '162'
) p
ON suborgs.meta_key = 'product_relationship' AND
suborgs.post_id = p.post_id;
然后JOIN
为您完成工作。
答案 1 :(得分:0)
一个简单但不漂亮的选择是添加一个"虚拟"子查询复制输出:
SELECT suborgs.meta_value
FROM (
SELECT suborgs2.*
FROM wp_postmeta suborgs2
WHERE suborgs2.meta_key = 'product_relationship'
) suborgs, (select 1 union select 2) as dummy
WHERE suborgs.post_id = '152'