在多个列中搜索多个值,仅显示匹配所有值的记录 MySQL
Searching multiple columns for multiple values showing records that match all values only MySQL
我在如何构造语句时遇到问题,因此它将 return 匹配多个列中多个值的记录,即使该值可能不在其他列中...是的,我知道让我解释一下,这听起来令人困惑。
假设我正在寻找 2 个值("this" 和 "that")。假设我正在 4 个不同的列中查找这些值。这是我想出的 2 个场景陈述,但都不能正常工作,我将对每一个进行解释。
使用 AND 运算符
SELECT * FROM table
WHERE (column1 LIKE '%this%'
AND column2 LIKE '%this%'
AND column3 LIKE '%this%'
AND column4 LIKE '%this%'
AND column1 LIKE '%that%'
AND column2 LIKE '%that%'
AND column3 LIKE '%that%'
AND column4 LIKE '%that%')
如果我对语句使用 AND 运算符,则每个值都必须在每一列中,否则语句将 return 没有记录。假设它在 column2
中找到 "this" 并在 column1
中找到 "that"。即使它在这 2 列中找到了这些值,这仍然 return 没有记录,因为在 column3
和 column 4
中找不到这些值
使用 OR 运算符
SELECT * FROM table
WHERE (column1 LIKE '%this%'
OR column2 LIKE '%this%'
OR column3 LIKE '%this%'
OR column4 LIKE '%this%'
OR column1 LIKE '%that%'
OR column2 LIKE '%that%'
OR column3 LIKE '%that%'
OR column4 LIKE '%that%')
如果我使用 OR 运算符,那么它将 return 所有包含任何列中任何值的记录,即使记录可能只包含这些值之一,而不是两者。
我试图用我的陈述完成的是仅 return 在任何列中同时包含 "this" 和 "that" 的记录,即使其他列可能不包含这些值。
希望这是有道理的。
使用 AND
和 OR
的组合。
SELECT * FROM table
WHERE (column1 LIKE '%this%'
OR column2 LIKE '%this%'
OR column3 LIKE '%this%'
OR column4 LIKE '%this%')
AND (column1 LIKE '%that%'
OR column2 LIKE '%that%'
OR column3 LIKE '%that%'
OR column4 LIKE '%that%')
我在如何构造语句时遇到问题,因此它将 return 匹配多个列中多个值的记录,即使该值可能不在其他列中...是的,我知道让我解释一下,这听起来令人困惑。
假设我正在寻找 2 个值("this" 和 "that")。假设我正在 4 个不同的列中查找这些值。这是我想出的 2 个场景陈述,但都不能正常工作,我将对每一个进行解释。
使用 AND 运算符
SELECT * FROM table
WHERE (column1 LIKE '%this%'
AND column2 LIKE '%this%'
AND column3 LIKE '%this%'
AND column4 LIKE '%this%'
AND column1 LIKE '%that%'
AND column2 LIKE '%that%'
AND column3 LIKE '%that%'
AND column4 LIKE '%that%')
如果我对语句使用 AND 运算符,则每个值都必须在每一列中,否则语句将 return 没有记录。假设它在 column2
中找到 "this" 并在 column1
中找到 "that"。即使它在这 2 列中找到了这些值,这仍然 return 没有记录,因为在 column3
和 column 4
使用 OR 运算符
SELECT * FROM table
WHERE (column1 LIKE '%this%'
OR column2 LIKE '%this%'
OR column3 LIKE '%this%'
OR column4 LIKE '%this%'
OR column1 LIKE '%that%'
OR column2 LIKE '%that%'
OR column3 LIKE '%that%'
OR column4 LIKE '%that%')
如果我使用 OR 运算符,那么它将 return 所有包含任何列中任何值的记录,即使记录可能只包含这些值之一,而不是两者。
我试图用我的陈述完成的是仅 return 在任何列中同时包含 "this" 和 "that" 的记录,即使其他列可能不包含这些值。
希望这是有道理的。
使用 AND
和 OR
的组合。
SELECT * FROM table
WHERE (column1 LIKE '%this%'
OR column2 LIKE '%this%'
OR column3 LIKE '%this%'
OR column4 LIKE '%this%')
AND (column1 LIKE '%that%'
OR column2 LIKE '%that%'
OR column3 LIKE '%that%'
OR column4 LIKE '%that%')