如何在mysql中使用where条件显示数据

30byixjq  于 2022-11-21  发布在  Mysql
关注(0)|答案(1)|浏览(164)

我有一个问题,我想显示数据使用的条件,这列在ON子句为status_riwayat=keluar和显示数据,status_riwayat=masuk不使用列tanggal条件,如下图。
表供应商

CREATE TABLE pj_detailsupplier (
id_detailsupplier int,
id_barang int,
id_supplier int,
no_batch varchar(255),
stok int,
tanggal date,
tgl_expired date,
status_detailsupplier int );

  INSERT INTO `pj_detailsupplier`(`id_detailsupplier`, `id_barang`, `id_supplier`, `no_batch`, `stok`, `tanggal`, `tgl_expired`, `status_detailsupplier`) VALUES ('13208','205','25','1','12','2022-01-01','2022-01-01','0')

表历史记录

CREATE TABLE pj_riwayat (
 id_riwayat int,
 id_detailsupplier int,
 jumlah int,
 keluar int,
 sisa int,
 tanggal date,
 status_riwayat varchar(255) );

 INSERT INTO `pj_riwayat`(`id_riwayat`, `id_detailsupplier`, `jumlah`, `keluar`, `sisa`, `tanggal`, `status_riwayat`) VALUES ('','13208','12','0','12','2022-09-02','masuk'), ('','13208','0','2','10','2022-11-14','keluar')

我想显示status_riwayat=masuk和status_riwayat=keluar中的数据,但使用where条件
我试过我的代码

SELECT * FROM pj_riwayat
  LEFT JOIN pj_detailsupplier ON pj_riwayat.id_detailsupplier=pj_detailsupplier.id_detailsupplier 
  AND month(pj_riwayat.tanggal)=11 AND year(pj_riwayat.tanggal)=2022 
  WHERE pj_detailsupplier.id_barang=205

但此代码仍然为false,因为我在ON子句中使用了此列条件我希望显示status_riwayat=masuk AND status_riwayat=keluar数据
我代码结果只显示一个数据

我希望通过使用上面的查询得到如下所示的两个数据

ni65a41a

ni65a41a1#

看来你需要在这:

SELECT t2.*, t3.*
          -- find id_detailsupplier which matches 
          -- id_barang=205 and tanggal=2022-11-XX
FROM pj_riwayat t1
JOIN pj_detailsupplier t2
  ON t1.id_detailsupplier=t2.id_detailsupplier 
          -- select all rows with found id_detailsupplier
          -- from another table copy
JOIN pj_riwayat t3
  ON t1.id_detailsupplier=t3.id_detailsupplier 
WHERE t2.id_barang=205
  AND month(t1.tanggal)=11
  AND year(t1.tanggal)=2022 
  AND t3.status_riwayat IN ('masuk', 'keluar')

https://dbfiddle.uk/upv6Kc4A

相关问题