MySQL 如果行存在 JOIN else SELECT

标签 mysql sql

我无法解决这个问题。

我将如何在 MySQL 中执行此操作?

我有 2 个表,一个包含产品,另一个包含链接到用户的产品列表。

如果用户有链接到他们的产品,则仅从产品表中选择那些产品。 如果用户没有链接到他们的任何产品,则选择所有产品。

我尝试了各种选择,但我似乎无法让它工作:(

编辑
表结构:

Products:
|  Supplier  |  partnumber  |  price  |
|------------|--------------|---------|
|      1     |      1b      |   4.00  |
|      4     |      13-f    |  12.00  |
|____________|______________|_________|


Lists
|   userid   |  partnumber  |
|------------|--------------|
|      37    |      1b      |
|____________|______________|

查询应该只选择 ID 为 1b 的产品。

使用其他 id 的用户应该同时选择 1b13-f

编辑 2

userid 存储在 PHP session 中,因此 users 表不应该是相关的!

最佳答案

您可以将存在行的部分合并到用户没有产品的部分:

select
  u.UserId,
  p.ProductId,
  p.ProductName
from
  Users u
  inner join UserProducts up on up.UserId = u.UserId
  inner join Products p on p.ProductId = up.ProductId
union all
select
  u.UserId,
  p.ProductId,
  p.ProductName
from
  Users u
  cross join Products p
where
  not exists (select 'x' from UserProducts up where up.UserId = u.UserId)  

除了使用 not exists,您也可以为此使用左连接。有人说这在 MySQL 中更快,尽管这取决于具体情况:

select
  u.UserId,
  p.ProductId,
  p.ProductName
from
  Users u
  inner join UserProducts up on up.UserId = u.UserId
  inner join Products p on p.ProductId = up.ProductId
union all
select
  u.UserId,
  p.ProductId,
  p.ProductName
from
  Users u
  cross join Products p
  left join UserProducts up on up.UserId = u.UserId
where
  up.UserId is null

无论哪种方式,查询看起来都很大,因为它们实际上是两个查询连接在一起。但因此它也具有可读性和合理的快速性。 Union all 几乎不会产生任何开销。

由于您的添加表明您已经有一个用户 ID,因此您的查询可能如下所示:

select
  p.ProductId,
  p.ProductName
from
  UserProducts up
  inner join Products p on p.ProductId = up.ProductId
where
  up.UserId = <YOURUSERID>
union all
select
  p.ProductId,
  p.ProductName
from
  Products
where
  not exists (select 'x' from UserProducts up where up.UserId = <YOURUSERID>) 

关于MySQL 如果行存在 JOIN else SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24182933/

相关文章:

mysql - 带有主元的 SUM 来计算总分

sql - 服务器迁移后从 TFS 和 SQL 中删除 "dead"用户帐户

sql - 如果不同表中的列匹配则更新值

sql日期选择

mysql - SQL条件返回特定日期范围

mysql - 如何使用以逗号分隔的行中的 where 子句数据来选择查询

mysql - 连接表时一对多连接

php - PDO MySQL 与 PHP Usort

MySQL 在连接函数时使用索引

sql - 如何为相同的项目添加相同的数字?