是否可以在SQL查询中编写SELECT CASE之后具有select语句的查询? 逻辑示例
SELECT Id, CASE WHEN level=2 THEN
(select something here)
else 0 end as Grade FROM CLASS
答案 0 :(得分:0)
基于PHP文档,您可以按照以下方式运行:
首先创建数据库连接:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
此if
语句正在检查表test
是否存在,然后将其删除 或 创建表{{1}使用test
id
INT
然后,如果条件是尝试,您在这里运行您的查询;他们有三个问题。
首先 - 计算表格中的总行数(等于0)
第二次 - 为表格添加值
第三次 - 再次计算总行数,这次将输出“1”
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
确保查询已正确构建
// this is what you may be asking?
// they add to their sql query
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
然后运行代码
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
的文档
请注意do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC)); // this will gather all records from the Database
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result()); // You can find the links for documentation for more_results() and next_result() below
?>
,因为您可以看到它们只是创建了多个查询,如果一切都是真的,它们将一起运行。
它将输出:
$sql
请注意,这不是我的代码,我是从here获得的
答案 1 :(得分:0)
您可以将第二个选择声明为变量。
例如:
DECLARE @var as int
SET @var = (SELECT COUNT(*) FROM table)
SELECT
Id,
CASE WHEN level=2 THEN @var else 0 end as Grade
FROM CLASS