我不是布尔表达式的学习者,但这似乎让我有点头疼。 在我的应用程序中,当我搜索用户时,我使用此MYSQL语句从我的数据中收到某些值。
SELECT `u3`.`username`,
CASE WHEN `u3`.`username` IS NULL THEN 'Not Existing'
ELSE 'Existing' END is_following
FROM `userinfo` `u3` WHERE `u3`.`username` LIKE '%".mysql_real_escape_string($data)."%' OR `u3`.`email` LIKE '%".mysql_real_escape_string($data)."%'
UNION
SELECT `u2`.`username`,
CASE WHEN `u2`.`username` IS NULL THEN 'Follow'
ELSE 'Following' END is_following
FROM
`userinfo` `u1` LEFT JOIN `followers` `f`
ON `u1`.`username` = `f`.`source_id`
LEFT JOIN `userinfo` `u2`
ON `f`.`destination_id` = `u2`.`username`
AND (`u2`.`username` LIKE '%".mysql_real_escape_string($data)."%' OR `u2`.`email` LIKE '%".mysql_real_escape_string($data)."%')
WHERE
`u1`.`username` = '$name'
现在上面的语法将返回这些值集,用户名和我自己的元数据。例如,它将返回
set of values 1: (davies and Existing)[if davies is in the userinfo table] AND (davies and Following)[if davies is following halex in the followers table]
OR
set of values 2: (null and Not Existing)[if davies is not in the userinfo table] AND (null and not followed)[davies does not exist]
OR
set of values 3: (davies and Existing)[if davies is in the userinfo table] AND (null and Not Following)[if davies is not following halex]
这些是我收到的一组值,我需要一个if语句来筛选,所以我可以向我的用户显示这个简单的信息
davies and Following
或davies and Follow[if davies is not following halex]
或User Does not Exist
现在我不确定我是否应该更改SOL语句的结构,或者我可以用if and else
语句更好地处理这个逻辑
这是我的if else
语句的结构,但它似乎不像我想要的那样工作
if(username != null && metadata.contains("Existing"))//user exist
{
value = username;
//user exists but skip
}else
{
if(username != null)
{
map = new HashMap<String, String>();
map.put(TAG_USERNAME, value);
map.put(TAG_METADATA, metadata);
listvalue.add(map);
}else
{
//user does not exist
Log.i("search ", "user does not exist");
}
}
以上代码属于android。 谢谢任何建议表示赞赏。再次感谢您。
答案 0 :(得分:0)
如果将查询分为两部分,该怎么办?一次查询一组信息将使事情变得更简单,更容易调试。
我可以想象做一些看起来像这样的东西(用伪代码):
query = "SELECT username
FROM `userinfo` `u3`
WHERE `u3`.`username` LIKE '%".mysql_real_escape_string($data)."%'
OR `u3`.`email` LIKE '%".mysql_real_escape_string($data)."%'"
var result = db.execute(query);
// set to true if the above query returns at least one row
bool user_exists = (result.RowCount() > 0)
var username = (user_exists)? result.GetRow().GetField("username") : null;
if(user_exists)//user exist
{
value = username;
//user exists but skip
} // ....
(我只复制了与你的UNION的第一个SELECT语句有关的功能;可以类似地重写与第二个语句相关的逻辑。)