根据第3个表的值对2个表中的数据进行排序

voase2hg  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(249)

我想从2个不同的表与union连接的数据排序,排序参数必须来自第3个表。(驱动程序>queno)
如果我对1个表中的数据进行排序,我将使用以下代码(非常有效):

SELECT quotedb.*
FROM   quotedb
       LEFT JOIN drivers
              ON quotedb.driver = drivers.id
ORDER  BY IF(queno = ''
              OR queno IS NULL, 1, 0)

所以当我加入两个表时,我尝试了这个,但没有成功。。。

(
 SELECT DISTINCT driver
 FROM            quotedb
 LEFT JOIN       drivers
 ON              quotedb.driver=drivers.id)
UNION ALL
          (
                          SELECT DISTINCT driver
                          FROM            packaging
                          LEFT JOIN       drivers
                          ON              packaging.driver=drivers.id )
ORDER BY
order by  IF(queno = ''
OR        queno IS NULL,1,0)

我需要做什么才能让它工作?。先谢谢你。

qni6mghb

qni6mghb1#

你得去拿那本书 queno 列也来自单个select查询。
请尝试以下操作:

(
 SELECT DISTINCT 
   qdb.driver AS driver, 
   d.queno AS queno 
 FROM quotedb AS qdb 
 LEFT JOIN drivers AS d ON qdb.driver = d.id
)
UNION ALL
(
 SELECT DISTINCT 
   p.driver AS driver, 
   d.queno AS queno 
 FROM packaging AS p 
 LEFT JOIN drivers AS d ON p.driver = d.id 
)
ORDER BY 
  (CASE WHEN queno = '' OR queno IS NULL THEN 1 
   ELSE 0
   END)

相关问题