简体   繁体   English

MYSQL选择带有连接,排序和空值

[英]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): 例如,我们有5个帖子(总和-上下总和):

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: 表2中没有帖子编号4,这就是为什么我的查询返回下一个帖子的原因:

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? 如果我无法更改数据库表的结构并无法在PHP中对结果进行排序,该如何解决此问题?

If you want to translate NULL value as number 0 in ordering, you have to enhance the ORDER BY clause like this: 如果NULL顺序将NULL值转换为数字0,则必须像下面这样增强ORDER BY子句:

ORDER BY IFNULL(t2.sum, 0) DESC

Remember, that this method prevents MySQL from using possible indexes. 请记住,这种方法会阻止MySQL使用可能的索引。 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. 无论如何,我认为这里的问题是,对于没有投票的帖子,我们的总和为null值。 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. 选择不重复可能需要更长的时间才能恢复,具体取决于数据量,例如,最好在可能的地方使用“ group by t2.id”,结果将相同,但会更快。 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 ? 为什么不使用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. 该函数将获得第一个非空值。

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

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