mysql - SQL 是有效的,但是有什么方法可以使它更小(包括 sqlfiddle)

标签 mysql sql

我有这个查询,它正在工作,我得到了我需要的东西

SQL 简述(下面提供的 sqlfiddle 中提供了更多示例)


# Case 1: Return those who do have active subscription (subscriptions and access_rights is for debugging only)
SELECT a.*,
  (GROUP_CONCAT(DISTINCT CONCAT (s.subscription_id,' => ',s.is_active) SEPARATOR ', ')) AS `subscriptions`,
  (GROUP_CONCAT(DISTINCT CONCAT (ar.access_right_id,' => ',ar.is_active) SEPARATOR ', ')) AS `access_rights`
FROM account a
  LEFT JOIN access_right ar USING (account_id)
  LEFT JOIN subscription s USING (account_id)
  LEFT JOIN access_right active_ar ON active_ar.account_id = a.account_id AND active_ar.is_active = 1
  LEFT JOIN access_right inactive_ar ON inactive_ar.account_id = a.account_id AND inactive_ar.is_active = 0
  LEFT JOIN subscription active_su ON active_su.account_id = a.account_id AND active_su.is_active = 1
  LEFT JOIN subscription inactive_su ON inactive_su.account_id = a.account_id AND inactive_su.is_active = 0
  WHERE (active_su.account_id IS NOT NULL)
  GROUP BY account_id;

# Case 2: Return those who do have non-active subscription (active needs to be excluded, nulls must be shown)
SELECT a.*,
  (GROUP_CONCAT(DISTINCT CONCAT (s.subscription_id,' => ',s.is_active) SEPARATOR ', ')) AS `subscriptions`,
  (GROUP_CONCAT(DISTINCT CONCAT (ar.access_right_id,' => ',ar.is_active) SEPARATOR ', ')) AS `access_rights`
FROM account a
  LEFT JOIN access_right ar USING (account_id)
  LEFT JOIN subscription s USING (account_id)
  LEFT JOIN access_right active_ar ON active_ar.account_id = a.account_id AND active_ar.is_active = 1
  LEFT JOIN access_right inactive_ar ON inactive_ar.account_id = a.account_id AND inactive_ar.is_active = 0
  LEFT JOIN subscription active_su ON active_su.account_id = a.account_id AND active_su.is_active = 1
  LEFT JOIN subscription inactive_su ON inactive_su.account_id = a.account_id AND inactive_su.is_active = 0
  WHERE (active_su.account_id IS NULL)
  GROUP BY account_id;

此外,类似的条件将应用于 access_right 表,并且还会有两种条件的组合

有什么办法可以缩短它吗?

http://sqlfiddle.com/#!9/14b347/15

最佳答案

如果您只需要他们是否有事件标志,则无需多次加入

# Case 1:
select a.*
from account a
LEFT JOIN subscription s on a.account_id = s.account_id
where s.is_active = 1;

# Case 2:
select a.*
from account a
where a.account_id not in 
    (select s.account_id from subscription s where s.is_active = 1);

关于mysql - SQL 是有效的,但是有什么方法可以使它更小(包括 sqlfiddle),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57205154/

相关文章:

MySQL - 条件查询,语句结果

MySQL触发if-else插入更新

c# - 如何从 C# 执行 .sql?

java - Android:是否应该以异步方式访问应用程序中的数据库?

php - 如何从php中删除json数据的while循环中的最后一个逗号

python - 在python中从mysql查询中制作一个excel文件

java - 选择值时 hibernate 出错

python - MemoryError 使用 json.dumps()

c# - 删除数据集 C# 上的一些数据

sql - 在 SQL 查询中使用 REPLACE 来获取换行符/回车符