1

I'm trying to do MySQL query to extract specific rows without the help of PHP if conditions,

okay,
i want to select a row where the variable is not in a specific row but here's the thing

$blocked_user = "aaron";

and in MySQL

+----------+-----------------------+
| id       | blocked               |
+----------+-----------------------+
| 1        | aaron,john            |

i want it to skip "aaron" while selecting and process to john
a false example :

SELECT * FROM table WHERE $blocked_user NOT IN blocked

What i was doing is get blocked content and seperate them using php explode function then using in_array and if to confirm its not there :

if(in_array($blocked_user, explode($row['blocked'])){
  exit;
}

but now i want to get rid of this and do it using a single query, how is it done ?

4

4 回答 4

4

您确实应该将每个 CSV 值放在不同的行中(可能在blocked表中),但是您可以这样做:

SELECT * 
FROM tbl
WHERE FIND_IN_SET('$blocked_user', blocked) = 0

如果$blocked_user包含在blocked列中的 CSV 列表中,则不会选择该行。


SQLFiddle 演示

于 2012-07-25T17:43:36.123 回答
1

我认为您正在寻找的是 LEFT OUTER JOIN,但这要求您将被阻止的名称存储在单独的行中。

例子:

+----------+-----------------------+
| id       | blocked               |
+----------+-----------------------+
| 1        | aaron                 |
| 2        | john                  |

然后您可以像这样在您的用户表上执行 LEFT OUTER JOIN:

SELECT * FROM users AS u
LEFT JOIN blocked as b
ON b.blocked = u.username
WHERE b.blocked IS NULL
于 2012-07-25T17:46:10.600 回答
1

您可能可以使用某种高级正则表达式 MySQL,但问题更深层次。你的表应该看起来更像这样:

| id | blocked |
----------------
| 1  |  aaron  |
| 1  |   john  |

其中当然id不是主键类型。

然后你可以这样做:

SELECT * FROM table WHERE id = 1 AND blocked NOT IN ('aaron')

根据您的编辑,如果您有第二张桌子,我们称之为data

SELECT * FROM data WHERE id = 1 AND id NOT IN (SELECT id FROM blocked_table WHERE blocked IN ('aaron'))
于 2012-07-25T17:39:23.033 回答
0

你可以试试

$sql = "SELECT * FROM table WHERE blocked NOT LIKE '%{$blocked_user}%'";
于 2012-07-25T17:42:58.107 回答