简体   繁体   中英

MySQL: joins, The used SELECT statements have a different number of columns

I know there are more questions about this but I can`t find the right answer for me.

This is my query:

$query = $mysql->query("(
                        SELECT questions.*, tags.tagData
                        FROM questions
                        LEFT JOIN tags
                        ON questions.id = tags.questId
                        )
                        UNION (
                        SELECT users.username
                        FROM users
                        LEFT JOIN questions
                        ON users.id = questions.ownerId
                        )
                    ");

I select all the questions in the table questions, also the tags but I save the ownerId as the id of the owner and I want the username to display. Now I get this error:

The used SELECT statements have a different number of columns

What am I doing wrong?

Why you need to do UNION ? question table is linked to User and you can use it in JOIN

SELECT questions.*, 
tags.tagData,
users.username
FROM questions
LEFT JOIN tags
ON  tags.questId = questions.id 
LEFT JOIN
users ON users.id = questions.ownerId
 `SELECT questions.*, tags.tagData
            FROM questions
            LEFT JOIN tags
            ON questions.id = tags.questId
            )
            UNION (
            SELECT users.username,questions.*
            FROM users
            LEFT JOIN questions
            ON users.id = questions.ownerId
            )`

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