简体   繁体   中英

Why does the group_concat bring one row with null values when there are no rows at all

I have a table post as p, table tags as pt and table tagsref as ptr.

tagsref will have the id's of post and tags table.

i used group_concat and i did not use group by clause because in the condition i am using an if condition to filter only one row (p.slug = 'once') assuming that since i had added the condition only one row will return. yes it did.

The problem is when there are no rows still i got a row with null values. in the following sql the last condition will not fetch any result because there are no rows with slug as 'none' so i should not get any result at all but i got one row with null values.

SELECT p.name, p.slug, GROUP_CONCAT(pt.name) as catz 
FROM post_tags pt, post_tagsref ptr, post p  
WHERE p.id = ptr.tid AND ptr.cid = pt.id  AND p.slug = 'none'

People suggested to use group by clause and mentioned that group_by aggregate functions will work even the group by clause is not specified but the result may be unpredictable.

i used group by and is working. yet.

post
-----
id  |   name    |   slug
1   |   sam     |   sam
2   |   do do   |   do-do

post_tags
--------------
id  |   name    |   slug
1   |   music   |   music
2   |   movies  |   movies
3   |   tv      |   tv

post_tagsref
------------    
pid |   pcid
1   |   2
1   |   1
2   |   1

The above is the table structure.

If there are no rows at all then why is group_concat returning one row with null values?

The reason for a question like this is to make sure what is what... :)

Reference:

Query is resulting in 1 row with null values when id is not found

Aggregate functions with no input tend to produce output nonetheless: the sum of no rows is zero, the count is zero as well, and the average is NULL . This kind of thing makes a lot of queries consistent, and should be the cause why you get NULL .

i did not use group by clause because in the condition i am using an if condition to filter only one row […]

You filter to only one post , but I assume there might be multiple tags for each post (else why would you use group_concat ), so the join will result in more than one row. Therefore you'll probably want to group by the post id.

Also note that as you are doing inner joins at the moment, a post with no tag at all won't be reported, so consider using left joins there.

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