MySQLで、同じテーブルまたは異なるテーブルの2つの列を比較する必要がある場合があります。 MySQLでは、演算子とネストされたクエリを使用して2つの列を簡単に比較できます。この記事では、MySQLの2つの列を比較する方法を見ていきます。
MySQLで2つの列を比較する方法
MySQLの2つの列を比較するために、さまざまなユースケースを見ていきます
同じテーブルの2つの列を比較する
次のテーブルがあるとしますsales(id、cost_price、selling_price) cost_priceを比較したい およびselling_price 列。
mysql> create table sales(id int, cost_price int, selling_price int);
mysql> insert into sales(id, cost_price, selling_price)
values(1, 135, 215),
(2,215, 145),
(3,310,100);
mysql> select * from sales;
+------+------------+---------------+
| id | cost_price | selling_price |
+------+------------+---------------+
| 1 | 135 | 215 |
| 2 | 215 | 145 |
| 3 | 310 | 100 |
+------+------------+---------------+
これは、テーブル(table1)の2つの比較列(column1、column2)に対する一般的なSQLクエリです。
mysql> select * from table1
where column1 not in
(select column2 from table1); 上記のクエリで、要件に応じてtable1、column1、column2を更新します。
ボーナスリード:MySQLでN行ごとに取得する方法
このクエリを適用して、2つの列を比較します cost_price およびselling_price 、および2つの列の間に不一致があるレコードを表示します。
mysql> select * from sales
where cost_price not in
(select selling_price from sales);
+------+------------+---------------+
| id | cost_price | selling_price |
+------+------------+---------------+
| 1 | 135 | 215 |
| 3 | 310 | 100 |
+------+------------+---------------+
2つの数値列を比較する場合は、数学演算子(<、>、<>)を使用することもできます。次に、cost_price>selling_price。
の行を表示する例を示します。mysql> select * from sales where cost_price>selling_price; +------+------------+---------------+ | id | cost_price | selling_price | +------+------------+---------------+ | 2 | 215 | 145 | | 3 | 310 | 100 | +------+------------+---------------+
ボーナスリード:MySQLに自動インクリメント列を追加する方法
異なるテーブルの2つの列を比較する
別のテーブルorders(id、cost_price、selling_price)もあるとします。
mysql> create table orders(id int, cost_price int, selling_price int);
mysql> insert into orders(id, cost_price, selling_price)
values(1, 235, 215),
(2,205, 105),
(3,320,120);
mysql> select * from orders;
+------+------------+---------------+
| id | cost_price | selling_price |
+------+------------+---------------+
| 1 | 235 | 215 |
| 2 | 205 | 105 |
| 3 | 320 | 120 |
+------+------------+---------------+ ボーナスリード:トップ5の無料データベース設計ツール
これは、異なるテーブルtable1とtable2の2つの列を比較するように変更された上記のSQLクエリです
mysql> select * from table1
where column1 not in
(select column2 from table2); 上記のクエリを適用して、 cost_priceを比較します。 販売の列 sales_priceのテーブル 注文 テーブル。
mysql> select * from sales
where cost_price not in
(select selling_price from orders);
+------+------------+---------------+
| id | cost_price | selling_price |
+------+------------+---------------+
| 1 | 135 | 215 |
| 3 | 310 | 100 |
+------+------------+---------------+
Ubiqを使用すると、データを簡単に視覚化し、リアルタイムのダッシュボードで監視できます。 Ubiqを無料でお試しください。