首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SQL从多个表中进行选择并按特定条件排序

SQL从多个表中进行选择并按特定条件排序
EN

Stack Overflow用户
提问于 2015-11-20 09:27:29
回答 1查看 151关注 0票数 0

我有两张桌子,customertickets

我希望能够从票表中选择,并通过以下方式订购:

tickets.priority然后是customer.category_priority然后是tickets.queue_time

我有一个疑问:

代码语言:javascript
复制
SELECT t.*
from tickets t
  JOIN customer c ON t.company = c.sequence
WHERE t.status <> 'Completed' AND t.queue = 'Y'
ORDER BY field(t.priority, 'Critical', 'High', 'Medium', 'Low'), t.queue_time ASC

,这对tickets.prioritytickets.queue_time非常有用。

但是我不知道如何合并customer.category_priority

因此,在customer表中,我有一些列的名称如下:

代码语言:javascript
复制
priority_computers
priority_telephone
priority_software

所有INT字段,其值为0、1或2。

tickets中的行有一个category列,它要么是ComputersTelephone,要么是Software,这就是链接到上面所需的内容。

因此,如果客户行的priority_computers为2,而tickets行为category = 'Computers',则该行将位于列表的首位,因为客户记录具有2的优先级,并且还将合并其他ORDER BY条件。

示例:

顾客:

  • A公司priority_computers =1
  • B公司priority_computers =2
  • C公司priority_computers =3

例一:

  • 机票1公司A优先=中型=计算机queue_time = 2015-11-20 08:00
  • 机票2公司B优先=中型=计算机queue_time =2015年-11-20 10:00:00
  • 票价3公司C优先=中型=计算机queue_time =2015年-11-20 08:30:00

这应按以下顺序输出:

  • 车票3
  • 车票2
  • 车票1

示例2:

  • 机票1公司B优先=高级类别=计算机 queue_time =2015年-11-20 12:00
  • 门票2公司A优先=中型=计算机queue_time = 2015-11-20 07:00:00
  • 机票3公司C优先=中型类别=计算机queue_time = 2015-11-20 07:00:00

这应按以下顺序输出:

  • 车票1
  • 车票3
  • 车票2
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-20 11:11:36

如果我正确理解了这一点,那么您的问题是,您必须以某种方式将数据与列名相匹配。

  • customer.priority_computers for ticket.category =“Computers”
  • customer.priority_telephone for ticket.category =“电话”
  • customer.priority_software for ticket.category =“Software”

这显示了一个数据库设计缺陷。应该有一个customer_priority表,每一行都包含一个客户、一个类别和相关的值。那你就可以加入了。

如前所述,您必须检查数据内容并决定在查询中使用的列:

代码语言:javascript
复制
SELECT t.*
from tickets t
  JOIN customer c ON t.company = c.sequence
WHERE t.status <> 'Completed' AND t.queue = 'Y'
ORDER BY field(t.priority, 'Critical', 'High', 'Medium', 'Low')
  , case t.category 
      when 'Computers' then c.priority_computers
      when 'Telephone' then c.priority_telephone
      when 'Software' then c.priority_software
    end
  , t.queue_time ASC

更新:如果您有一个customer_priority表,下面是您将要编写的查询。您知道,您的查询不需要知道存在哪些类别以及如何处理它们。

代码语言:javascript
复制
SELECT t.*
from tickets t
  JOIN customer c ON t.company = c.sequence
  JOIN customer_priority cp ON cp.customer_id = c.sequence
                            AND cp.category = t.category
WHERE t.status <> 'Completed' AND t.queue = 'Y'
ORDER BY field(t.priority, 'Critical', 'High', 'Medium', 'Low')
  , cp.priority_value
  , t.queue_time ASC

此外:如前所述,拥有一个表customer是很奇怪的,但是在tickets中,它不是一个客户,而是一个公司,在customer表本身中,它也不是一个客户号或ID,而是一个序列。这就降低了查询的可读性。我建议,如果可能的话,你可以改变名字,所以它们是一致的。

此外,您的查询不应该知道“关键”和“高”的含义。在每个优先级都有名称和值的情况下,应该有一个优先级表,因此查询可以简单地选择值并使用它,而不必知道其他任何关于优先级的信息。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33823130

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档