我一直在试图找出加入这些查询的最佳方式,而且我很难过 - 我会在这方面寻求帮助!
查询1为我提供了我想要的行 - 查询2为我提供了另一个表中的条目,其中数据相对于查询1中的每一行
我似乎无法构建一个正确的语句来返回包含来自查询1的每一行中查询2的结果的行。注意:查询1中的“object_id AS id”=查询2中的“post_id”
查询1:
SELECT LEFT(post_content, 40) AS excerpt, id, post_title, guid FROM wp_posts
WHERE id IN
(SELECT object_id AS id FROM wp_term_relationships WHERE term_taxonomy_id = 74)
查询2:
SELECT post_id,
MAX(CASE WHEN meta_key = 'allowed' THEN meta_value END) allowed,
MAX(CASE WHEN meta_key = 'amenities' THEN meta_value END) amenities,
MAX(CASE WHEN meta_key = 'trail-type' THEN meta_value END) trailtype,
MAX(CASE WHEN meta_key = 'weatherlat' THEN meta_value END) weatherlat,
MAX(CASE WHEN meta_key = 'weatherlon' THEN meta_value END) weatherlon
from wp_postmeta WHERE post_id = ***id from Query 1***
查询1返回以下内容:
excerpt | id | post_title | guid
-----------------------------------------
data | 1 | example title | link
data | 2 | example title | link
data | 3 | example title | link
查询2返回以下内容:
post_id | allowed | amenities | trailtype | weatherlat | weatherlon
------------------------------------------------------------------------------
1 | BOOL | a, b, c | 1 | 53.12 | -24.123
期望的结果是:
excerpt | id | post_title | guid | allowed | amenities | trailtype | weatherlat | weatherlon
-----------------------------------------
data | 1 | example title | link | BOOL | a, b, c | 1 | 53.12 | -24.123
data | 2 | example title | link | BOOL | d, e, f | 2 | 23.67 | 56.42
data | 3 | example title | link | BOOL | a, b, c | 1 | 56.152 | -50.123
答案 0 :(得分:3)
这只是在语法上组合你的查询:
SELECT LEFT(a.post_content, 40) AS excerpt, a.id, a.post_title, a.guid,
MAX(CASE WHEN meta_key = 'allowed' THEN b.meta_value END) allowed,
MAX(CASE WHEN meta_key = 'amenities' THEN b.meta_value END) amenities,
MAX(CASE WHEN meta_key = 'trail-type' THEN b.meta_value END) trailtype,
MAX(CASE WHEN meta_key = 'weatherlat' THEN b.meta_value END) weatherlat,
MAX(CASE WHEN meta_key = 'weatherlon' THEN b.meta_value END) weatherlon
FROM wp_posts a
LEFT JOIN wp_postmeta b ON a.id = b.post_id
WHERE a.id IN
(SELECT object_id AS id FROM wp_term_relationships WHERE term_taxonomy_id = 74)
答案 1 :(得分:0)
这个where
声明不会有效吗?
where post_id in (SELECT object_id AS id FROM wp_term_relationships WHERE term_taxonomy_id = 74)
在第一个查询中,id
设置为这些object_id
值之一。因此,外部查询不会添加任何内容(或取消任何内容)。
答案 2 :(得分:0)
经过多次痛苦,痛苦,并且提出了3-4个未完整答案的问题(很多部分答案 - 感谢所有人),我已经构建了声明,以便返回的行完全是我想要的。
SELECT LEFT(a.post_content, 100) AS excerpt, a.id, a.post_title, a.guid,
MAX(CASE WHEN b.meta_key = 'allowed' THEN b.meta_value END) allowed,
MAX(CASE WHEN b.meta_key = 'amenities' THEN b.meta_value END) amenities,
MAX(CASE WHEN b.meta_key = 'trail-type' THEN b.meta_value END) trailtype,
MAX(CASE WHEN b.meta_key = 'weatherlat' THEN b.meta_value END) weatherlat,
MAX(CASE WHEN b.meta_key = 'weatherlon' THEN b.meta_value END) weatherlon
FROM wp_posts a
LEFT JOIN wp_postmeta b ON a.id = b.post_id
WHERE a.id IN (SELECT object_id AS id FROM wp_term_relationships WHERE term_taxonomy_id = 74) group by b.post_id
结果是完美的! 请参阅: