简体   繁体   中英

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.

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). 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). 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. 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.

To get your desired result, you only got to invert your logic and use a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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