联合多个 table 与不同的列按日期排序

Union multiple table with different column for order by date

我搜索了执行此请求的解决方案SQL 因为这不起作用,like_supplier table 和类似的产品 table 可以正常工作但是当我添加table 评论不起作用,我知道 table 评论中没有同一列,但我如何正确地做到这一点?提前致谢。

SELECT DISTINCT * 
FROM (
    (SELECT DISTINCT lp.customer_id, lp.`date`, lp.`product_id`, lp.`classes`, Null as `comment` 
    FROM 
        `like_product` as lp, 
        `supplier_products` as sp 
    WHERE 
        sp.`product_id` = lp.`product_id` 
        AND sp.`supplier_id`=".$customer_id.")

    UNION DISTINCT

    (SELECT DISTINCT ls.`customer_id`,ls.`date`, Null as `product_id`, ls.`classes`, Null as `comment` 
    FROM 
        `like_supplier` as ls, 
        `supplier_products` as sp 
    WHERE 
        sp.`supplier_id`=".$customer_id." 
        AND sp.`product_id` = ls.`product_id`)

    UNION DISTINCT

    (SELECT com.`sender_id`, com.`date`, com.`product_id`, com.`classes`, com.`comment` 
    FROM `comments` as com)) as a

ORDER BY a.`date` desc

尝试澄清所有别名和列名:

SELECT DISTINCT 
  a.id, 
  a.`date`, 
  a.product_id,
  a.classes,
  a.comment
FROM (
  (SELECT DISTINCT 
    lp.customer_id as id,
    lp.`date` as `date`,
    lp.`product_id` as product_id,
    lp.`classes` as classes,
    Null as comment 
   FROM 
     `like_product` as lp
   INNER JOIN 
     (SELECT *

     FROM
       `supplier_products`  
     WHERE 
       supplier_id=".$customer_id."
     ) as sp
   ON
     sp.`product_id` = lp.`product_id`
   )

    UNION DISTINCT

    (SELECT DISTINCT 
       ls.`customer_id` as id,
       ls.`date` as `date`, 
       Null as `product_id`, 
       ls.`classes`, 
       Null as `comment` 
    FROM 
        `like_supplier` as ls
    INNER JOIN
      (SELECT
         *
       FROM
         `supplier_products` 
       WHERE 
         supplier_id=".$customer_id." 
      ) as sp 
    ON sp.`product_id` = ls.`product_id`)

    UNION DISTINCT

    (SELECT 
       com.`sender_id` as id, 
       com.`date` as `date`, 
       com.`product_id` as product_id,
       com.`classes` as classes,
       com.`comment` as comment
    FROM `comments` as com
    )
  ) as a

ORDER BY a.`date` desc