简体   繁体   English

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

[英]How to union different multiple selects in one query?

Is it possible to combine all the tables in one or maybe two queries? 是否可以将所有表合并为一个或两个查询?

I tried to use union but i need access to each row in query. 我尝试使用联合,但我需要访问查询中的每一行。

And the biggest problem for me is to sort all of this with ORDER BY. 对我来说,最大的问题是使用ORDER BY进行排序。

For example i need to print first query rows in one div, second query rows in another div and so on.. 例如,我需要在一个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);

Yes, it's possible to do what you ask. 是的,可以按照您的要求做。 You need UNION ALL between your queries. 您的查询之间需要UNION ALL You also need to use the same aliases for your columns in each of the items you're UNION ing together. 您还需要在每个你的项目中使用相同的别名为您列UNION荷兰国际集团一起。

Here's what will do the job for you. 这是将为您完成的工作。 I didn't repeat all your subqueries 我没有重复您所有的子查询

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

Notice how all the columns are made to conform to each other by using the same aliases? 请注意,如何使用相同的别名使所有列彼此一致?

If you want these items deduplicated, use UNION rather that UNION ALL . 如果要对这些项目进行重复数据删除,请使用UNION而不是UNION ALL It's a little slower because of the deduplication process, but you're only handling dozens of rows so that's likely not a problem. 由于重复数据删除过程的原因,它有点慢,但是您只处理几十行,所以这可能不是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM