简体   繁体   中英

MYSQL select with join, sorting and null values

I have two tables.

Table 1.
========
id
post
--------

Table 2.
========
id
post_id
thumbs_sum
--------

Query looks like:

SELECT DISTINCT(t2.id), t2.sum, t1.id
FROM table1 t
    LEFT JOIN table2 t2 ON t2.post_id = t1.id
ORDER BY t2.sum DESC

For example, we have 5 posts (sum - sum of thumbs up and down):

1. sum = 3
2. sum = 1
3. sum = 5
4. sum = null
5. sum = -2

Post number 4 hasn't any record in Table 2, that's why my query return the next:

1. sum = 5
2. sum = 3
3. sum = 1
4. sum = -2
5. sum = null

How to decide this problem if I haven't ability to change the structure of database tables and to sort result in PHP?

If you want to translate NULL value as number 0 in ordering, you have to enhance the ORDER BY clause like this:

ORDER BY IFNULL(t2.sum, 0) DESC

Remember, that this method prevents MySQL from using possible indexes. So ordering thousands of records may be slow.

I'm trying to figure out what is the actual question here. "How to decide this problem" is a little abstruse.

Anyway, I assume, the problem here is we have null values as thumbs sum for posts that have no votes. When we order them, we'll probably want to replace nulls with zeros.

SELECT DISTINCT(t2.id), t2.sum, t1.id
FROM table1 t
    LEFT JOIN table2 t2 ON t2.post_id = t1.id
ORDER BY IFNULL(t2.sum, 0) DESC

select distinct can take a lot longer to come back depending on the data volume, you would be better to use "group by t2.id" for example where you can, the result will be the same but will be faster. also look into indexing your tables to improve performance.

answering your question, i would use

order by ifnull(t2.sum, 0) DESC

your other option is to set a default value of zero in the database table design that way this will never be a problem ;)

Why don't you use COALESCE ?

SELECT DISTINCT(t2.id), COALESCE(t2.sum, 0), t1.id
FROM table1 t
    LEFT JOIN table2 t2 ON t2.post_id = t1.id
ORDER BY t2.sum DESC

that function will get the first non-null value.

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