简体   繁体   English

MYSQL-显示查询结果计数而不会丢失实际结果条目

[英]MYSQL - displaying query result counts without losing actual result entries

Sorry if this is a really dumb question but I'm not too familiar with MYSQL syntax. 抱歉,这是一个非常愚蠢的问题,但是我对MYSQL语法不太熟悉。

I've historically been running: 我一直在跑步:

USE hg19; 
SELECT DISTINCT (name2), txStart, txEnd 
FROM refGene 
WHERE name2 LIKE '[genename]';

which would output all entries and it was fine, except if I was looking for an entry that didn't exist, I would get a blank (which just so happened to be the same result if I disconnected from the server). 它将输出所有条目,这很好,除非我正在寻找一个不存在的条目,否则我将得到一个空白(如果断开与服务器的连接,结果也是一样)。 This was leading to a bunch of downstream issues when I couldn't actually detect if an entry didn't exist vs my internet disconnected me. 当我实际上无法检测到条目是否存在而我的互联网断开了我的连接时,这导致了一系列下游问题。

So instead I decided to try: 因此,我决定尝试:

USE hg19; 
SELECT *, count(*) AS results 
FROM (
  SELECT DISTINCT (name2), txStart, txEnd 
  FROM refGene 
  WHERE name2 LIKE 'TP53'
) a;

This would now give me a 0 for results if it didn't exist (and if it didn't connect it'd remain blank). 现在,如果结果不存在(如果未连接,则为空白),结果将为0。 However, now for whatever reason it only displays one entry no matter what (If I query for TP53 for example, it should have two distinct entries -> however, it will give me results:2 but only display one of them). 但是,无论出于何种原因,现在无论如何它都只显示一个条目(例如,如果我查询TP53,它应该有两个不同的条目->但是,它将给我结果:2,但只显示其中一个)。 Is there a way around this? 有没有解决的办法? I would still like to have it displaying all distinct results. 我仍然希望它显示所有不同的结果。

COUNT() is a aggregate function that works on groups of rows. COUNT()是适用于行组的聚合函数。 Without a GROUP BY clause only MySQL accepts such a statement and will return arbitrary values in the not aggregated columns - and return just one row, as you've seen. 如果没有GROUP BY子句,只有MySQL会接受这样的语句,并且将在未聚合的列中返回任意值-如您所见,仅返回一行。

To get your desired result, you only got to invert your logic and use a LEFT JOIN 为了获得理想的结果,您只需反转逻辑并使用LEFT JOIN

SELECT 
    a.results,
    b.*
FROM
    (SELECT COUNT(*) results FROM refGene r1 WHERE a.name2 LIKE 'TP53') a
LEFT JOIN (
    SELECT
        *
    FROM
        refGene r2
    WHERE
        name2 LIKE 'TP53'
) b
ON
   a.result IS NOT NULL;

If your "main" query returns no row there will be a 0 (zero) in the result column an NULL values in the columns of your "main" query. 如果“主”查询不返回任何行,则结果列中将为0(零),而“主”查询的列中将为NULL值。

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

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