MySQL:使用一个查找表查询具有不同查找ID的两个字段

时间:2014-08-20 03:08:31

标签: mysql sql join

如果已经使用了第二个lookup.id,如何改进现有查询以显示正确的查找值。如果我使用派生表会更好吗?子查询?有人可以教我吗?

问题:

RECORDS TYPE    TYPE_DESC   PROCESS_ID  STATUS  QUEUE_DESC
1       1       Queued      55          4       Queued
1       2       Cancelled   84          7       Cancelled

我的目标:

RECORDS TYPE    TYPE_DESC   PROCESS_ID  STATUS  QUEUE_DESC
1       1       Initial     55          4       Queued
1       2       Follow Up   84          7       Cancelled

现有查询:

SELECT 
    COUNT(q.id) as records,
    q.type,
    l.description AS type_desc,
    q.process_id,
    q.status,
    l.description AS queue_desc
FROM
    queues q,
    lookups l
WHERE
    l.id = q.status
GROUP BY q.status;

为了更好地理解我的问题,请参阅sqlfiddle条目: http://sqlfiddle.com/#!2/6b7d10/6

由于

3 个答案:

答案 0 :(得分:1)

您必须两次加入“查找”表。

SELECT COUNT(q.id)    AS records
      ,q.type
      ,l1.description AS type_desc
      ,q.process_id
      ,q.status
      ,l2.description AS queue_desc
FROM queues  q
    ,lookups l1
    ,lookups l2
WHERE l1.id = q.type
  and l2.id = q.status
GROUP BY q.status;

就是这样。

答案 1 :(得分:1)

试试这个:

select count(q.id) as records, 
q.type, a.description, q.process_id, q.status, 
b.description as qdesc
from 
queues q
inner join lookups a on q.type = a.id
inner join lookups b on q.status = b.id
group by q.status

您需要与lookups两次加入 - 一次获取类型并再次获取状态。请注意使用带有ON子句的显式连接语法。

答案 2 :(得分:1)

我认为这是您想要的查询:

SELECT COUNT(q.id) as records,
       q.type,
       lt.description AS type_desc,
       q.process_id,
       q.status,
       ls.description AS queue_desc
FROM queues q join
     lookups ls
     on ls.id = q.status and ls.key = 'status' join
     lookups lt
     on lt.id = q.type and lt.key = 'type'
GROUP BY q.status;

请注意,这可确保密钥类型与联接的值匹配。