我正在执行一个mysql查询。我正在加入4桌。我希望只有当p.location_id不等于0时才会将两条粗线连接到查询中。我希望它们在p.location_id等于0时不会被执行
SELECT p. *
FROM property p, property_type pt, location l, city c
WHERE p.status =1
AND (
pt.prop_name LIKE '%dlf%'
OR p.furnish LIKE '%dlf%'
OR p.description LIKE '%dlf%'
OR p.bed LIKE '%dlf%'
OR p.term_condition LIKE '%dlf%'
OR p.bedroom LIKE '%dlf%'
OR p.property_type LIKE '%dlf%'
OR c.city_name LIKE '%dlf%'
**OR l.loct_name LIKE '%dlf%'**
)
AND p.prop_id = pt.prop_id
AND p.city = c.city_id
**AND p.location_id = l.loct_id**
ORDER BY sortnum
我有什么方法可以实现这一目标。
答案 0 :(得分:0)
将查询保存在字符串中,并根据执行前的条件将字符串连接起来....
伪代码是
sql = "the query";
if(condition)
{
sql.="what you want to add"
}
编辑: 试试这个 SELECT p。 * ......... IF(p.location_id!= 0,AND p.location_id = l.loct_id,NULL)ORDER BY sortnum 编辑2:
SELECT p. * FROM property p, property_type pt, location l, city c WHERE p.status =1 AND (pt.prop_name LIKE '%dlf%' OR p.furnish LIKE '%dlf%' OR p.description LIKE '%dlf%' OR p.bed LIKE '%dlf%' OR p.term_condition LIKE '%dlf%' OR p.bedroom LIKE '%dlf%' OR p.property_type LIKE '%dlf%' OR p.property_type LIKE '%dlf%' OR c.city_name LIKE '%dlf%' OR (IF(p.location_id !=0 , l.loct_name LIKE '%dlf%',NULL))) AND p.prop_id = pt.prop_id AND p.city = c.city_id AND (IF(p.location_id != 0),p.location_id = l.loct_id,NULL) ORDER BY shortnum
答案 1 :(得分:0)
SELECT p.*
FROM property p, property_type pt, location l, city c
WHERE p.status =1
AND (
pt.prop_name LIKE '%dlf%'
OR p.furnish LIKE '%dlf%'
OR p.description LIKE '%dlf%'
OR p.bed LIKE '%dlf%'
OR p.term_condition LIKE '%dlf%'
OR p.bedroom LIKE '%dlf%'
OR p.property_type LIKE '%dlf%'
OR c.city_name LIKE '%dlf%'
OR (p.location_id <> 0 AND l.loct_name LIKE '%dlf%')
)
AND p.prop_id = pt.prop_id
AND p.city = c.city_id
AND (p.location_id = 0 OR p.location_id = l.loct_id)
ORDER BY sortnum
您只需要更多逻辑条件。代码仍然存在,但是当你想要的条件发生时SQL不会运行它。