如何在一个查询中结合不同的多个选择?

时间:2014-10-04 23:47:33

标签: mysql

是否可以在一个或两个查询中组合所有表?

我尝试使用union,但我需要访问查询中的每一行。

对我来说最大的问题是使用ORDER BY对所有这些进行排序。

例如,我需要在一个div中打印第一个查询行,在另一个div中打印第二个查询行,等等。

(SELECT 
      link as RelLink, 
      date as RelDate,
      title as RelTitle 
   FROM torrent 
   WHERE moderate = 1 
   ORDER BY date DESC LIMIT 0,12),
(SELECT 
      torrent as TorLink1, 
      date as TorDate1, 
      title as TorTitle1 
   FROM torrents 
   WHERE moderate = 1 AND genre = 1 
   ORDER BY date DESC LIMIT 10),
(SELECT 
      date as TorDate2, 
      torrent as TorLink2, 
      title as TorTitle2 
   FROM torrents 
   WHERE moderate = 1 AND genre = 2 
   ORDER BY date DESC LIMIT 10),
(SELECT 
      link as NewsLink1, 
      date as NewsDate1, 
      title as NewsTitle1 
   FROM news 
   WHERE moderate = 1
   ORDER BY date DESC LIMIT 0,10),
(SELECT 
      link as NewsLink2, 
      date as NewsDate2,
      title as NewsTitle2 
   FROM news 
   WHERE moderate = 1 
   ORDER BY date DESC LIMIT 10,10);

1 个答案:

答案 0 :(得分:0)

是的,可以按照你的要求去做。您的查询之间需要UNION ALL。您还需要在UNION组合的每个项目中为列使用相同的别名。

以下是为您完成工作的内容。我没有重复你所有的子查询

SELECT Link, Date, Title 
FROM (
    SELECT link as Link, date as Date, title as Title 
      FROM torrent  WHERE moderate = 1 ORDER BY date DESC LIMIT 0,12
    UNION ALL
    SELECT torrent as Link, date as Date, title as Title 
      FROM torrents  WHERE moderate = 1 AND genre = 1 ORDER BY date DESC LIMIT 10
    UNION ALL
    SELECT torrent as Link, date as Date, title as Title
      FROM torrents WHERE moderate = 1 AND genre = 2 ORDER BY date DESC LIMIT 10 
    UNION ALL
   /* etc etc */
) AS query
ORDER BY Date DESC

注意如何使用相同的别名使所有列相互符合?

如果您希望对这些项目进行重复数据删除,请使用UNION而不是UNION ALL。由于重复数据删除过程,它有点慢,但你只处理了几十行,所以这可能不是问题。