从表中的多个列中搜索特定值

时间:2019-03-29 11:18:35

标签: sql sql-server

我有一个带有示例列的表::


<link rel="stylesheet" href="style.css">
<div class="frm">
    <form action="action.php" method="POST" class="log" id="log">

        <h4>Log In</h4>

        <label for="loginl"> Username: </label>
        <input type="login" name="loginl" id="login">

        <label for="password"> Password: </label>
        <input type="password" name="password" id="password">

        <label for="password"> Mail: </label>
        <input type="mail" name="mail" id="mail">

        <input type="button" value="Submit" id="button">

    </form>
</div>

<?php $loginl = $_POST["loginl"]; $password = $_POST["password"]; $mail = $_POST["mail"]; $text = $_POST["text"]; $loginl = stripcslashes($loginl); $password = stripcslashes($password); $mail = stripcslashes($mail); $text = stripcslashes($text); $loginl = mysql_real_escape_string($loginl); $password = mysql_real_escape_string($password); $mail = mysql_real_escape_string($mail); $text = mysql_real_escape_string($text); $db = mysql_connect("localhost", "root", "usbw", "armus"); mysql_set_charset($db, "utf8"); $result = mysql_query("SELECT * from users where loginl = '$loginl' and password = '$password' and mail = '$mail'") or die("Failed to query database ".mysql_error()); $row = mysql_fetch_array($result); if ($row['loginl'] == $loginl && $row["password"] == $password && $row["mail"] == $mail){ echo "Login Success!!! Welcome ". $row['text'] ; } else { echo "failed to login!"; } ?> )中只有一列将不包含“ P_ID P1_QUALITY P2_QUALITY P3_QUALITY 1 A C C 2 A+ C C 3 A C C 4 B+ C C 5 A- C C ”,就像这里的P1_QUALITY, P2_QUALITY, P3_QUALITY,而第二次可能是C。我必须获取不包含值'C'的P1_QUALITY。我该怎么办?

3 个答案:

答案 0 :(得分:1)

您可以使用apply

select t.*, q.*
from t cross apply
     (select qual, col
      from (values (P1_QUALITY, 'P1_QUALITY'), (P2_QUALITY, 'P2_QUALITY'), (P3_QUALITY, 'P3_QUALITY')
           ) v(qual, col)
      where qual <> 'C'
     ) q;

答案 1 :(得分:1)

您也可以尝试使用CASE WHEN

SELECT CASE 
WHEN P2_QUALITY <> 'C' and P3_QUALITY <> 'C' THEN 'P1_QUALITY'
WHEN P1_QUALITY <> 'C' and P3_QUALITY <> 'C' THEN 'P2_QUALITY'
WHEN P1_QUALITY <> 'C' and P2_QUALITY <> 'C' THEN 'P3_QUALITY'
END AS 'Result'
FROM TABLE_NAME

答案 2 :(得分:1)

CASENOT LIKE一起使用,可以获得第一列的名称,该列的值不以'C'开头

(假设可能还有值“ C +”或“ C-”)

SELECT t.*,
(CASE 
 WHEN P1_QUALITY NOT LIKE 'C%' THEN 'P1_QUALITY'
 WHEN P2_QUALITY NOT LIKE 'C%' THEN 'P2_QUALITY'
 WHEN P3_QUALITY NOT LIKE 'C%' THEN 'P3_QUALITY'
 END) AS [NotC]
FROM YourTable t;

如果您希望查询限制为不带3个'C'的内容?
只需添加一个WHERE子句,像这样:

WHERE CONCAT(P1_QUALITY, P2_QUALITY, P3_QUALITY) NOT LIKE 'C%C%C%'