我遇到了一种情况,我必须在支票上显示帖子并取消选中这些条款。
分配了条款的帖子。我有条件'区域'和'美食'现在我必须选择有'XYZ'区和'ABC'美食的帖子。
我试过的查询: -
SELECT p.ID, p.post_title
FROM wp_posts p
LEFT JOIN `wp_term_relationships` t
ON p.ID = t.object_id
LEFT JOIN `wp_term_taxonomy` tt
ON t.term_taxonomy_id = tt.term_taxonomy_id
WHERE tt.term_id IN (".$area.")
OR tt.term_id IN (".$cuis.")
GROUP BY t.object_id
HAVING COUNT( t.term_taxonomy_id ) = 2
LIMIT 0,7
这里显示了wp_term_taxonomy的结构: -
问题是单个表和单个列,并在值之间应用AND运算符。
wp_term_relationship
object_id | wp_term_taxonomy_id | term_order
==============================================
134 | 36 | 0
______________________________________________
135 | 36 | 0
wp_posts
ID | post_title |
==================================
1 | Hello world! |
__________________________________
2 | Test |
wp_term_taxnomy
term_taxonomy_id term_id taxonomy description parent count
=============================================================================
1 1 category ------ 0 2
答案 0 :(得分:1)
假设我们有3个表:
| test1 | | test1_to_test2 | | test2 |
|-------+ +----------------| +-------|
| id |-----| test1_id | +----| id |
| test2_id |----+
正是你所拥有的结构。
内容:
test1
+----+-------+
| id | value |
+----+-------+
| 1 | val1 |
| 2 | val2 |
+----+-------+
test1_to_test2
|----------+----------|
| test1_id | test2_id |
|----------+----------|
| 1 | 1 |
| 1 | 2 |
| 2 | 1 |
|----------+----------|
test2
|----+
| id |
|----+
| 1 |
| 2 |
|----+
我们需要从test1表中选择值,test1_to_test2中的行包含(test2_id = 1)AND(test2_id = 2)。所以,我们想要这个:
+----+-------+
| id | value |
+----+-------+
| 1 | val1 |
+----+-------+
为此,我们将任务分为两个子任务:
1.从test1_to_test2中选择test1_id
,其中包含两行:
SELECT
test1_id
FROM
test1_to_test2
WHERE
test1_to_test2.test2_id IN (1,2)
GROUP BY
test1_id
HAVING
COUNT(test1_id) = 2
2.使用子查询和IN运算符(它是我们需要的SQL)从test1中选择适当的行:
SELECT
test1.id,
test1.`value`
FROM
test1
WHERE
test1.id IN
(
SELECT
test1_id
FROM
test1_to_test2
WHERE
test1_to_test2.test2_id IN (1,2)
GROUP BY
test1_id
HAVING
COUNT(test1_id) = 2
)
我们得到了我们需要的东西:
+----+-------+
| id | value |
+----+-------+
| 1 | val1 |
+----+-------+
对你的表使用相同的方法,你将得到具有“XYZ”区域和烹饪“ABC”的帖子。
答案 1 :(得分:0)
最好的办法是做两个连接,每个连接一个:
SELECT p.ID, p.post_title
FROM wp_posts p
LEFT JOIN `wp_term_relationships` t
ON p.ID = t.object_id
LEFT JOIN `wp_term_taxonomy` tarea
ON t.term_taxonomy_id = tt.term_taxonomy_id and tt.term_id IN (".$area.")
LEFT JOIN `wp_term_taxonomy` tcuis
ON t.term_taxonomy_id = tt.term_taxonomy_id and tt.term_id IN (".$cuis.")
WHERE tarea.description = 'XYZ' and
tcuis.descriptoin = 'ABC'
GROUP BY t.object_id
LIMIT 0,7 ;
此外,您可以将left join
更改为inner join
s - 无论如何where
子句。 left join
对“或”条件而不是“和”条件有用。