好的,我要再试一次......这次我肯定是对的。对此感到抱歉。 :(
表1 :
+----+---------+------------+------+
| id | item_id | product_id | type |
+----+---------+------------+------+
table2,table3,table4 :
+----+---------+
| id | item_id |
+----+---------+
这是我的主要查询:
$sql = "SELECT t1.* FROM table1 AS t1, table2 AS t2 WHERE t2.id = '1' AND
t2.item_id = t1.item_id AND t1.type NOT IN ('type1', 'type2') LIMIT 5";
$a = mysql_query($sql);
while($b = mysql_fetch_assoc($a))
现在我想整合这两个查询:
第一次查询:
AND IF t1.type = 'type3'
然后
SELECT t3.item_id FROM table3 AS t3 WHERE t3.id = t1.product_id AND
t3.item_id NOT IN (SELECT t2.item_id FROM table2 AS t2 WHERE t2.id = '1')
仅当上述查询中的此语句t3.item_id NOT IN (...)
为真时,才会显示主查询中的t1.id
。但是,如果t3.item_id is IN (...)
,则应将其从结果中排除。
第二次查询:
AND IF t1.type = 'type4'
然后
SELECT t4.item_id FROM table4 AS t4 WHERE t4.id = t1.product_id AND
t4.item_id NOT IN (SELECT t2.item_id FROM table2 AS t2 WHERE t2.id = '1')
与第一次查询相同。
这一切都适合一个查询吗?我只在一个查询中需要它,所以我知道在下一页显示哪些结果,例如LIMIT 5,5
答案 0 :(得分:0)
在mysql中应用flow control flow structure
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
END CASE
或者:
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
END CASE
答案 1 :(得分:0)
我不确定我是否理解正确,但我认为应该使用(NOT) EXISTS
:
SELECT t1.*
FROM table1 AS t1
JOIN table2 AS t2
ON t2.item_id = t1.item_id
WHERE t2.id = '1'
AND t1.type NOT IN ('type1', 'type2')
AND NOT ( t1.type = 'type3'
AND EXISTS
( SELECT t3.item_id
FROM table3 AS t3
WHERE t3.id = t1.product_id
AND t3.item_id NOT IN
( SELECT t2.item_id
FROM table2 AS t2
WHERE t2.id = '1' )
)
)
AND NOT ( t1.type = 'type4'
AND EXISTS
( SELECT t4.item_id
FROM table4 AS t4
WHERE t4.id = t1.product_id
AND t4.item_id NOT IN
( SELECT t2.item_id
FROM table2 AS t2
WHERE t2.id = '1' )
)
)
ORDER BY WhatYouWant
LIMIT x,y