我有一套简单的序列号产品。如果产品已售出,其序列号将放在sold_items
中,而所有已存在的商品仍保留在all_items
。
一些示例数据:
all_items
id | serial_number | product_name | product_price
1 | XXXXXXXXXXX01 | Laptop | 199
2 | XXXXXXXXXXX02 | Tablet | 99
sold_items
id | serial_number | sold_time
1 | XXXXXXXXXXX02 | [TIMESTAMP]
我试图用我的查询做这样的事情:
SELECT
all_items.* ,
(JOIN sold_items ON sold_items.serial_number = all_items.serial_number) AS is_sold
FROM all_items
在这种情况下,预期输出为
[
0=>[
'id'=>1,
'serial_number'=>XXXXXXXXXXX01,
'product_name'=>Laptop,
'product_price'=>199,
'is_sold'=>0
],
1=>[
'id'=>1,
'serial_number'=>XXXXXXXXXXX02,
'product_name'=>Tablet,
'product_price'=>99,
'is_sold'=>1
]
]
使用单个查询是否可以轻松实现这一目标?
答案 0 :(得分:2)
使用LEFT JOIN
并测试另一个表中的ID是否为空。
SELECT a.*, s.id IS NOT NULL AS is_sold
FROM all_items AS a
LEFT JOIN sold_items AS s ON a.serial_number = s.serial_number