合并两个 SELECT 个查询(如果找不到)
Combine two SELECT queries IF one is not found
我希望将两个 select 查询有效地组合成一个查询,同时考虑到性能。
我希望第一个 SELECT
获得一行。如果该行 不 存在,则 运行 另一个 SELECT
查询。如果第一个查询中确实存在该行,则使用第一个查询中找到的行,不要 run/get 第二个查询中的任何内容。
这是我的两个查询:
$stmt = $dbh->prepare("SELECT * FROM users WHERE unique_code = :unique_code LIMIT 1");
$stmt->bindParam(':unique_code', $uniqueCode);
$stmt->execute();
$row = $stmt->fetch();
if(!$row) { // If row does not exist
$stmt = $dbh->prepare("SELECT * FROM users WHERE birthday = :birthday LIMIT 1");
$stmt->bindParam(':birthday', $birthday);
$stmt->execute();
$row = $stmt->fetch();
}
我该怎么做?
编辑:示例数据:
id | unique_code | birthday
-----------------------------
1 123 1987-05-20
2 456 1955-03-10
您可以通过组合您的 WHERE
条件,然后根据匹配的条件进行排序,在一个查询中执行此操作:
SELECT *
FROM users
WHERE unique_code = :unique_code OR birthday = :birthday
ORDER BY unique_code = :unique_code DESC
LIMIT 1
如果唯一代码匹配,unique_code = :unique_code
将为 1,并且由于我们按降序排序,该行将排在第一位(并且是 LIMIT
子句之后唯一剩下的行。如果唯一代码不匹配,那么如果有任何行,它们必须在生日那天匹配。
我希望将两个 select 查询有效地组合成一个查询,同时考虑到性能。
我希望第一个 SELECT
获得一行。如果该行 不 存在,则 运行 另一个 SELECT
查询。如果第一个查询中确实存在该行,则使用第一个查询中找到的行,不要 run/get 第二个查询中的任何内容。
这是我的两个查询:
$stmt = $dbh->prepare("SELECT * FROM users WHERE unique_code = :unique_code LIMIT 1");
$stmt->bindParam(':unique_code', $uniqueCode);
$stmt->execute();
$row = $stmt->fetch();
if(!$row) { // If row does not exist
$stmt = $dbh->prepare("SELECT * FROM users WHERE birthday = :birthday LIMIT 1");
$stmt->bindParam(':birthday', $birthday);
$stmt->execute();
$row = $stmt->fetch();
}
我该怎么做?
编辑:示例数据:
id | unique_code | birthday
-----------------------------
1 123 1987-05-20
2 456 1955-03-10
您可以通过组合您的 WHERE
条件,然后根据匹配的条件进行排序,在一个查询中执行此操作:
SELECT *
FROM users
WHERE unique_code = :unique_code OR birthday = :birthday
ORDER BY unique_code = :unique_code DESC
LIMIT 1
如果唯一代码匹配,unique_code = :unique_code
将为 1,并且由于我们按降序排序,该行将排在第一位(并且是 LIMIT
子句之后唯一剩下的行。如果唯一代码不匹配,那么如果有任何行,它们必须在生日那天匹配。