这是我的问题:即使第二个表没有相应的条目,也可以从 2 个 db 表中获取查询结果。
这是我在 SQL 中使用的一些示例代码
SELECT DISTINCT apps.id, apps.*, req.status
FROM applications AS apps, requests AS req
WHERE apps.id = {$app_id}
但问题是它不会提取没有 request.status 值/条目的应用程序,所以问题是:是否可以修改这个简单的查询以提取所有 application.* 行的结果,即使有是没有对应的requests.status 行/条目?
编辑如下:
所以这是我收到的反馈中的新查询(这很好用)
SELECT DISTINCT
apps.*, req.status
FROM
applications AS apps
LEFT JOIN requests AS req ON (req.app_id = apps.id AND req.uid = {$user_id})
WHERE
apps.id = {$app_id}
但是:当我在 where 子句中添加一个新表达式来过滤请求状态时,我遇到了与隐式查询相同的问题,我没有得到结果(查询如下)
SELECT DISTINCT
apps.*, req.status
FROM
applications AS apps
LEFT JOIN requests AS req ON (req.app_id = apps.id AND req.uid = {$user_id})
WHERE
apps.id = {$app_id}
AND
(req.status = 2 OR req.status = 5)
另一个编辑
这是要查看的更新代码。现在的问题是,如果我添加一个子查询,子查询将提取所有行,然后将 NULL 作为状态列的值,但是一旦我添加 WHERE status != 2 它只会删除所有条目,这不应该还有所有为空的行吗?因为 null 显然是 != 2。
SELECT DISTINCT
apps . *
FROM
(SELECT
apps . *, req.status
FROM
appstore_app AS apps
LEFT JOIN app_user_request AS req ON (req.uid = 187 AND req.appid = apps.appid)
WHERE
apps.appid > 0 AND apps.company_id = 122) AS apps
WHERE
apps.status != 2
ORDER BY apps.average_user_rating DESC
最终编辑
感谢您的帮助!
这是对我有用的最终查询:
SELECT
apps.*, req.status
FROM
appstore_app AS apps
LEFT JOIN
app_user_request AS req ON (req.uid = {$user_id} AND req.appid = apps.appid AND (req.status IS NULL OR req.status != 2))
WHERE
apps.appid > 0 AND apps.company_id = {$company_id}