如何从另一个查询中获取mySql查询结果

时间:2018-09-12 11:04:47

标签: mysql sql concat

我有3个mySql表:

shop
        id1  shop_name 
         1   shop1
         2   shop2
         3   shop3

    queue_number
        id2  id_shop  queue_current_number
         1      1             32
         2      2             56
         3      3             22

    queue_customer
        id3  id_queue   your_number   
         1      1            33
         2      1            34
         3      1            35
         4      2            57

我从以下查询开始:

SELECT *
FROM shop
LEFT JOIN queue_number ON queue_number.id_shop = shop.id1
WHERE id_shop = 1
GROUP BY id2

我的结果:

shop1> queue_current_number = 32

shop2> queue_current_number = 56

shop3> queue_current_number = 22

我想要这样的结果:

shop1> queue_current_number = 35

shop2> queue_current_number = 57

shop3> queue_current_number = 22

谢谢!

2 个答案:

答案 0 :(得分:0)

尝试使用子查询:

SELECT shop.id1, shop.name, COALESCE(younumber,queue_current_number) as q_current_number
FROM shop
LEFT JOIN queue_number ON queue_number.id_shop = shop.id1
left join
(select id_queue,max(your_number) as younumber
from queue_customer group by id_queue)c on c.id_queue= shop.id1
WHERE id_shop = 1

答案 1 :(得分:0)

我假设您正在通过使用queue_customer而不是queue_number(使用COALESCE ...),或者想要两者中的最大值(使用IF(COALESCE ...))来寻找最大值。 / p>

    SELECT COALESCE( c.your_number, n.queue_current_number ) 
    /* or maybe you want IF( COALESCE( c.your_number, 0 ) > COALESCE( n.queue_current_number, 0 ), c.your_number, n.queue_current_number ) */
    FROM shop s
    LEFT JOIN queue_number n   ON s.id1 = n.id_shop 
                              AND NOT EXISTS( SELECT * FROM queue_number n2
                                              WHERE n.id_shop = n2.id_shop
                                                AND n.queue_current_number < n2.queue_current_number )
    LEFT JOIN queue_customer c ON n.id2 = c.id_queue
                              AND NOT EXISTS( SELECT * FROM current_number c2
                                              WHERE c.id_queue = c2.id_queue
                                                AND n.your_number < n2.your_number )
    WHERE s.id_shop = 1