0

我正在执行一个 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

有什么办法可以做到这一点。

4

2 回答 2

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

于 2012-10-01T07:33:06.747 回答
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 不会运行它。

于 2012-10-01T08:26:59.880 回答