我有两张桌子,customer和tickets
我希望能够从票表中选择,并通过以下方式订购:
tickets.priority然后是customer.category_priority然后是tickets.queue_time
我有一个疑问:
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.priority和tickets.queue_time非常有用。
但是我不知道如何合并customer.category_priority
因此,在customer表中,我有一些列的名称如下:
priority_computers
priority_telephone
priority_software所有INT字段,其值为0、1或2。
tickets中的行有一个category列,它要么是Computers、Telephone,要么是Software,这就是链接到上面所需的内容。
因此,如果客户行的priority_computers为2,而tickets行为category = 'Computers',则该行将位于列表的首位,因为客户记录具有2的优先级,并且还将合并其他ORDER BY条件。
示例:
顾客:
例一:
这应按以下顺序输出:
示例2:
这应按以下顺序输出:
发布于 2015-11-20 11:11:36
如果我正确理解了这一点,那么您的问题是,您必须以某种方式将数据与列名相匹配。
这显示了一个数据库设计缺陷。应该有一个customer_priority表,每一行都包含一个客户、一个类别和相关的值。那你就可以加入了。
如前所述,您必须检查数据内容并决定在查询中使用的列:
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表,下面是您将要编写的查询。您知道,您的查询不需要知道存在哪些类别以及如何处理它们。
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,而是一个序列。这就降低了查询的可读性。我建议,如果可能的话,你可以改变名字,所以它们是一致的。
此外,您的查询不应该知道“关键”和“高”的含义。在每个优先级都有名称和值的情况下,应该有一个优先级表,因此查询可以简单地选择值并使用它,而不必知道其他任何关于优先级的信息。
https://stackoverflow.com/questions/33823130
复制相似问题