0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MySQLエラー「The used SELECT statements have a different number of columns」

Last updated at Posted at 2023-08-01

起こったこと

My SQLにてSELECT文で、あるカラムの値を取得しようとした際にThe used SELECT statements have a different number of columnsのエラーが発生した。

原因

SELECT文にほしいカラムを追加したが、よく見るとUNIONにて結合を行っており、UNION側のカラム数とSELECT文のカラム数が合わなくなっていた。

UNIONとは

複数の SELECT 文によってデータをそれぞれ取得し、その結果を結合した上で1つのデータとして取得する場合に使う。
LEFT JOINやRIGHT JOIN などの左右結合でなく、縦に結合するためカラム数が一致しないといけない。

例 SELECT id, name, age from uranohoshi UNION SELECT id, name, age from otonokizaka

table:uranohoshi

id name age
1 watanabe 17
2 kunikida 15
3 matsuura 18

table:otonokizaka

id name age
1 takasaka 17
2 nishikino 15
3 ayase 18

結合後

id name age
1 watanabe 17
2 kunikida 15
3 matsuura 18
1 takasaka 17
2 nishikino 15
3 ayase 18

まとめ

The used SELECT statements have a different number of columnsのエラーを見るのは初めてだったが、UNIONで結合を行っている場合以外では起きないエラーっぽい?
このエラーが出た場合はUNION結合をしていないか確認する必要あり。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?